栈的链表实现
1/**
2 * 使用链表实现一个栈,顺序栈,没有容量限制
3 *
4 * @author wangy
5 * @version 1.0
6 * @date 2021/6/24 / 16:34
7 */
8public class StackByList {
9
10 private SingleNodeList data;
11
12 public StackByList() {
13 this.data = new SingleNodeList();
14 }
15
16 int count() {
17 return data.size();
18 }
19
20 void push(int e) {
21 data.insertHead(e);
22 }
23
24 Object pop() {
25 return data.removeHead();
26 }
27
28 Object top(){
29 return data.getHead();
30 }
31
32 // 按出栈顺序打印栈内元素
33 void printAll(){
34 data.printAll();
35 }
36
37 public static void main(String[] args) {
38 StackByList stack = new StackByList();
39 stack.push(1);
40 stack.push(2);
41 stack.push(3);
42 stack.push(4);
43 stack.printAll();
44 stack.pop();
45 stack.printAll();
46 }
47
48 /************************* 链表实现 ***************/
49
50 class SingleNodeList {
51 private Node head;
52
53 private int size;
54
55 public SingleNodeList() {
56 this.head = null;
57 this.size = 0;
58 }
59
60 int size() {
61 return size;
62 }
63
64 boolean isEmpty() {
65 return size == 0;
66 }
67
68 Object getHead() {
69 return head.data;
70 }
71
72 void insertHead(Object o) {
73 Node n = new Node(o);
74 n.next = head;
75 head = n;
76 size++;
77 }
78
79 Object removeHead(){
80 if(head == null) throw new ArrayStoreException("Stack Empty!");
81 Node h = this.head;
82 this.head = this.head.next;
83 size--;
84 return h.data;
85 }
86
87 void printAll(){
88 System.out.print("[");
89 Node h = head;
90 for (int i = 0; i < size -1 ; i++) {
91 System.out.print(h.data + ",");
92 h = h.next;
93 }
94 System.out.println(h.data + "]");
95 }
96
97 class Node {
98 Object data;
99 Node next;
100
101 public Node(Object data) {
102 this.data = data;
103 this.next = null;
104 }
105 }
106 }
107}