📜  使用链表的 java 堆栈 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:27.438000             🧑  作者: Mango

代码示例1
class StackUsingLinkedlist {
              private class Node {
                int data;
                Node next;
              }
            
              Node top;
            
              StackUsingLinkedlist() {
                this.top = null;
              }

            public void push(int data) {
              Node newNode = new Node();
              newNode.data = data;
              newNode.next = top;
              top = newNode;
            }
            
            public boolean isEmpty() {
              return top == null;
            }
            
            public int peek() {
              if (!isEmpty()) {
                return top.data;
              } else {
                System.out.println("Stack is empty");
                return -1;
              }
            }
            
            public void pop() {
              if (top == null) {
                System.out.print("\nStack empty");
                return;
              }
              top = top.next;
            }
            
            public void display() {
              if (top == null) {
                System.out.print("\nStack empty");
                exit(1);
              } else {
                Node node = top;
                while (node != null) {
                  System.out.printf("%d->", node.data);
                  node = node.next;
                }
              }
            }