复制代码
 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   唠叨的Soar  阅读(32)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示