1 public class LinkedListStackDemo {
 2     public static void main(String[] args) {
 3         LinkedListStack linkedListStack = new LinkedListStack();
 4         Node node1 = new Node(1,"李明");
 5         Node node2 = new Node(2,"王鹏");
 6         Node node3 = new Node(3,"张华");
 7         Node node4 = new Node(4,"代月");
 8         linkedListStack.push(node1);
 9         linkedListStack.push(node2);
10         linkedListStack.push(node3);
11         linkedListStack.push(node4);
12         System.out.println("入栈后从栈顶开始显示栈的情况:");
13         linkedListStack.list();
14         try{
15             Node res = linkedListStack.pop();
16             System.out.println("出栈的节点为:");
17             System.out.println(res);
18         }
19         catch (Exception e) {
20             System.out.println(e.getMessage());
21         }
22 
23         System.out.println("出栈后情况显示:");
24         linkedListStack.list();
25     }
26 }
27 class LinkedListStack{
28     Node head = new Node(0,"");
29     public boolean isEmpty() {
30         return head.next == null;
31     }
32     //使用头插法入栈,方便出栈
33     public void push(Node node) {
34         if(head.next == null) {
35             head.next = node;
36             return;
37         }
38         node.next = head.next;
39         head.next = node;
40     }
41     //出栈
42     public Node pop() {
43         if(isEmpty()) {
44             throw new RuntimeException("栈为空,无法出栈");
45         }
46         Node res = head.next;
47         head.next = head.next.next;
48         return res;
49     }
50     //从栈顶显示数据
51     public void list() {
52         if(isEmpty()) {
53             System.out.println("栈为空,无数据显示");
54             return;
55         }
56         Node temp = head.next;
57         while(temp != null) {
58             System.out.println(temp);
59             temp = temp.next;
60         }
61     }
62 }
63 class Node {
64     public int no;
65     public String name;
66     public Node next;
67     public Node(int no, String name) {
68         this.no = no;
69         this.name = name;
70     }
71 
72     @Override
73     public String toString() {
74         return "Node{" +
75                 "no=" + no +
76                 ", name='" + name + '\'' +
77                 '}';
78     }
79 }

 

posted on 2022-05-04 21:37  唠叨的Soar  阅读(42)  评论(1)    收藏  举报