1 Star 0 Fork 0

besti1923 / beishizhi

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Chain_1.java 2.36 KB
一键复制 编辑 原始数据 按行查看 历史
好名字 提交于 2020-11-21 22:10 . 6.4/5更新
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()); //跳过该节点,达到删除的目的
}
}
Java
1
https://gitee.com/besti1923/beishizhi.git
git@gitee.com:besti1923/beishizhi.git
besti1923
beishizhi
beishizhi
master

搜索帮助