LinkedStack.java
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
public class LinkedStack { private static class Node { int data; Node next; public Node(int data){ this.data = data; } public Node(int data, Node next){ this.data = data; this.next = next; } } private Node top; private int count = 0; public int size(){ return count; } public void push(int d){ if (top == null) top = new Node(d); else top = new Node(d, top); count++; } public int peek(){ return top.data; } public int pop(){ int temp = top.data; top = top.next; count--; return temp; } @Override public String toString(){ String retVal = "Linked stack of size: " + count + '\n'; for (Node temp = top; temp != null; temp = temp.next) retVal += temp.data + " "; return retVal; } // Testing our LS: public static void main(String[] args){ LinkedStack ll = new LinkedStack(); ll.push(10); ll.push(45); ll.push(23); System.out.println(ll); System.out.println(ll.peek()); System.out.println(ll.pop()); System.out.println(ll); } } |
LinkedQueue.java
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
public class LinkedQueue { private static class Node { int data; Node next; public Node(int data){ this.data = data; } public Node(int data, Node next){ this.data = data; this.next = next; } } private Node head, tail; private int count = 0; public int size(){ return count; } public void enqueue(int d){ if (head == null) tail = head = new Node(d); else tail = tail.next = new Node(d); count++; } public int peek(){ return head.data; } public int dequeue(){ int temp = head.data; head = head.next; count--; return temp; } @Override public String toString(){ String retVal = "Linked queue of size: " + count + '\n'; for (Node temp = head; temp != null; temp = temp.next) retVal += temp.data + " "; return retVal; } // Testing our LQ: public static void main(String[] args){ LinkedQueue ll = new LinkedQueue(); ll.enqueue(10); ll.enqueue(45); ll.enqueue(23); System.out.println(ll); System.out.println(ll.peek()); System.out.println(ll.dequeue()); System.out.println(ll); } } |