/*
*@author 旧梦吖
*@version 1.0
*/
public class Test {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
SingleLinkedList_ sll = new SingleLinkedList_();
boolean loop = true;
while(loop){
System.out.println("1. 添加");
System.out.println("2. 删除");
System.out.println("3. 列表");
System.out.println("4. 退出");
int num = myScan.nextInt();
switch(num) {
case 1:
System.out.println("请输入添加的id:");
sll.add(new Node(myScan.nextInt()));
break;
case 2:
sll.deleteByTop();
break;
case 3:
sll.list();
break;
case 4:
loop = false;
break;
default:
System.out.println("输入有误");
}
System.out.println("======================");
}
System.out.println("退出了程序...");
}
}
class SingleLinkedList_ {
Node head = new Node(-1);
Node headTemp = head;//辅助指针
Node top = head; //模拟栈顶的
public void add(Node node){
findLast().next = node;
top = node;
}
public void deleteByTop(){
headTemp = head;
while (true){
if(headTemp.next == null){
return;
}
if(headTemp.next.id == top.id){
headTemp.next = null; //使栈顶的前指向的后指向指向null
top = headTemp;//使原来栈顶的前指向变为栈顶
return;
}
headTemp = headTemp.next;
}
}
public Node findLast(){
headTemp = head;
while (true){
if(headTemp.next == null){
break;
}
headTemp = headTemp.next;
}
return headTemp;
}
public void list(){
headTemp = head;
while (true){
if(headTemp.next == null){
break;
}
System.out.println(headTemp.next);
headTemp = headTemp.next;
}
}
}
class Node {
//基础属性
int id;
//下一节点
Node next;
//构造
public Node(){};
public Node(int id){
this.id = id;
}
//toString
@Override
public String toString() {
return "Node{" +
"id=" + id +
'}';
}
}
(内容仅供自学记载)