代码拉取完成,页面将自动刷新
package Lei;
import java.util.Scanner;
public class Chain_1 {
public static Chain head;
public static int nBeiShizhi = 0;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
//先输入并创建表头
System.out.println("Enter numbers("+(nBeiShizhi + 1)+").Type stop if you want to stop.");
String str = scan.nextLine();
Chain chain0 = new Chain(Integer.parseInt(str));
head = chain0;
//一直输入并实现连接,直到输入“stop”
do{
nBeiShizhi++;
System.out.println("Enter numbers("+(nBeiShizhi + 1)+").Type stop if you want to stop.");
str = scan.nextLine();
if(str.equals("stop")){ //防止整数型链表输入字符串导致错误
break;
}
Chain chain = new Chain(Integer.parseInt(str));
connect(head, chain);
}while (!str.equals("stop"));
//删除
System.out.println("Delete?(y/n)");
if (scan.nextLine().equals("y")){
System.out.println("Please enter the node you want to delete:");
int node = scan.nextInt();
delete(head, node);
}
//输出
PrintLinkedList(head);
System.out.println("Total number of elements:" + nBeiShizhi);
}
//链表之间的连接,尾插法,遍历
public static void connect(Chain head, Chain chain2){
Chain head2 = head;
while (head2.getNext() != null){
head2 = head2.getNext();
}
head2.setNext(chain2);
}
//用来输出的静态方法
public static void PrintLinkedList(Chain head){
Chain temp = head;
String list = "";
while (temp != null){
list = list + " " + temp.getElement();
temp = temp.getNext();
}
System.out.println(list);
}
//删除
public static void delete(Chain head, int node){
Chain temp = head;
if(node == 1) { //删除头节点
Chain_2.head = head.getNext();
}
else { //遍历至要删除的节点
for(int i = 1; i < node - 1; i++){
temp = temp.getNext();
}
}
temp.setNext(temp.getNext().getNext()); //跳过该节点,达到删除的目的
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。