Advertisement
Guest User

LinkedStack

a guest
Feb 17th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1.  
  2. import java.util.EmptyStackException;
  3.  
  4.  
  5. public class LinkedStack<T> {
  6.  
  7.     Node head;
  8.     int count;
  9.  
  10.     public void push(T item) {
  11.         if (head == null) {
  12.             // The stack is empty
  13.             Node newNode = new Node(item, null);
  14.             head = newNode;
  15.         } else {
  16.             // Stack is not empty, create a new node at the top of the stack
  17.             // The new item's next link goes to the "old" head
  18.             Node newNode = new Node(item, head);
  19.  
  20.             // Now we can re-assign the link to the new head
  21.             head = newNode;
  22.         }
  23.     }
  24.  
  25.     public T pop() throws EmptyStackException {
  26.         // TODO: Write code to add pop functionality
  27.         if (head == null) {
  28.             throw new EmptyStackException();
  29.         }
  30.         else{
  31.             T result = head.getData();
  32.             head = head.getNext();
  33.             count--;
  34.             return result;
  35.         }
  36.     }
  37.  
  38.     public T peek() {
  39.         // TODO: Write code to add peek functionality
  40.         if (head == null) {
  41.             throw new EmptyStackException();
  42.         }
  43.         else {
  44.             return head.data;
  45.         }
  46.     }
  47.  
  48.     public int length() {
  49.         Node n = head;
  50.         int length = 0;
  51.         while (n != null) {
  52.             length++;
  53.             n = n.next;
  54.         }
  55.         return length;
  56.     }
  57.  
  58.     @Override
  59.     public String toString() {
  60.         // TODO: Write code to add toString functionality
  61.         return "";
  62.     }
  63.  
  64.     // Nested class Node
  65.     private class Node {
  66.         T data;
  67.         Node next;  //pointer to the next node
  68.  
  69.         // Constructor for inner class Node
  70.         Node(T data, Node next) {
  71.             this.data = data;
  72.             this.next = next;
  73.         }
  74.  
  75.         // Setters & Getters for inner class Node
  76.         public T getData() {
  77.             return data;
  78.         }
  79.         public void setData(T data) {
  80.             this.data = data;
  81.         }
  82.         public Node getNext() {
  83.             return next;
  84.         }
  85.         public void setNext(Node next) {
  86.             this.next = next;
  87.         }
  88.     }
  89.  
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement