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 67 |
public class LinkedStack<T> { private class Node<T> { T data; Node<T> next; public Node(T data){ this.data = data; } public Node(T data, Node<T> next){ this(data); this.next = next; } public String toString(){ return "" + data; } } private Node<T> top; private int count; public LinkedStack(){ top = null; count = 0; } public LinkedStack(T d){ top = new Node<T>(d); count = 1; } public int length() { return count; } public boolean isEmpty(){ return top == null; } public void push(T d){ top = new Node<T>(d, top); count++; } public T peek() { return top.data; } public T pop() { T t = top.data; top = top.next; count--; return t; } public String toString(){ String retVal = "Linked Stack with " + count + " nodes: "; for (Node<T> temp = top ; temp != null ; temp = temp.next){ retVal += temp + " "; } return retVal; } } |
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 67 68 69 70 71 72 73 |
import java.util.Iterator; public class LinkedQueue<T> { private class Node<T> { T data; Node<T> next; public Node(T data){ this.data = data; } public Node(T data, Node<T> next){ this(data); this.next = next; } public String toString(){ return "" + data; } } private Node<T> head, tail; private int count; public LinkedQueue(){ head = tail = null; count = 0; } public LinkedQueue(T d){ head = tail = new Node<T>(d); count = 1; } public int length() { return count; } public boolean isEmpty(){ return head == null; } public void enqueue(T d){ if (isEmpty()) head = tail = new Node<T>(d); else tail = tail.next = new Node<T>(d); count++; } public T peek() { return head.data; } public T dequeue() { T t = head.data; head = head.next; count--; if (isEmpty()) tail = null; return t; } public String toString(){ String retVal = "Linked Queue with " + count + " nodes: "; for (Node<T> temp = head ; temp != null ; temp = temp.next){ retVal += temp + " "; } return retVal; } } |