CS3343/3341
 Analysis of Algorithms 
Spring 2012
  Linked List   
Used as
Stack and Queue
(Java Version)


Linked List, with Inherited Stack and Queue (Java Version)

Linked List, with Inherited Stack and Queue
Linked List ItselfInherited Stack and Queue along with Test Code
// ListNode.java: node for a linked list
public class ListNode {
   public int data;
   public ListNode next;

   public ListNode(int newdata) {
      // would be this way by default
      data = newdata;
      next = null;
   }
}

// LinkdedList.java: basic linked list public class LinkedList { private ListNode first; // front, top private ListNode last; // rear public LinkedList() { last = null; first = null; } public void addLast(int dataItem) { // or add to rear, i.e. enqueue if (last == null) { // empty linked list last = new ListNode(dataItem); first = last; } else { // case of non-empty linked list last.next = new ListNode(dataItem); last = last.next; } } public void addFirst(int dataItem) { // or add to front, i.e. dequeue, or push ListNode newNode = new ListNode(dataItem); newNode.next = first; first = newNode; if (last == null) // adding to empty list last = newNode; } public int removeFirst() { // or pop int valueToReturn = first.data; first = first.next; if (first == null) last = null; return valueToReturn; } public boolean empty() { return first == null; } public void printList() { // first to last, or front to rear ListNode temp = first; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } public void printReverse() { printReverse0(first); System.out.println(); } public void printReverse0(ListNode temp) { // last to first, or rear to front if (temp != null) { printReverse0(temp.next); System.out.print(temp.data + " "); } } }
// Stack.java: inherited from linked list
public class Stack extends LinkedList{

   public void push(int dataItem) {
      addFirst(dataItem);
   }

   public int pop() {
      return removeFirst();
   }
}

// Queue.java: inherited from linked list public class Queue extends LinkedList{ public void enqueue(int dataItem) { addLast(dataItem); } public int dequeue() { return removeFirst(); } }
// ListTest.java: test stack and queue public class ListTest{ public static void main(String[] args) { int[] a = {2, 3, 5, 7, 11, 13}; Queue q = new Queue(); for (int i = 0; i < a.length; i++) q.enqueue(a[i]); System.out.println("Queue:"); q.printList(); q.printReverse(); int t = q.dequeue(); System.out.print(t + " "); t = q.dequeue(); System.out.print(t + "\n"); Stack s = new Stack(); for (int i = 0; i < a.length; i++) s.push(a[i]); System.out.println("Stack:"); s.printList(); s.printReverse(); t = s.pop(); System.out.print(t + " "); t = s.pop(); System.out.print(t + "\n"); } }
Common Output
Queue:
2 3 5 7 11 13 
13 11 7 5 3 2 
2 3
Stack:
13 11 7 5 3 2 
2 3 5 7 11 13
13 11


Revision date: 2011-12-17. (Please use ISO 8601, the International Standard Date and Time Notation.)