CS3343/3341 Analysis of Algorithms Spring 2012 |
Linked List
Used as Stack and Queue (Java Version) |
[Please see the C Version of this part of the recitation for C code, but you should use the directions and picture below.]
The purpose of this part of the recitation is to practice pointer manipulations involving linked lists. For this purpose I'm using a program that implements a linked list is such a way that the list can be used either as a stack or a queue. This is primarily an exercise and an example of algorithms involving pointers. It is not an example of how stacks and queues should be implemented. In the Java implementation below, one would probably want to make the data structures generic. In addition, with only the functionality below, there is not benefit to the added complexity of linked lists. Here is a picture of the basic structure of the lists worked on below:Linked List, with Inherited Stack and Queue (Java Version) | |
---|---|
Linked List Itself | Inherited 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; } // Can put in another constructor // public ListNode() { ... } // if you want to or need to. } | // Stack.java: inherited from linked list public class Stack extends LinkedList{ public void push(int dataItem) { addFirst(dataItem); } public int pop() { return removeFirst(); } // Could add main function here // for testing. (Not required.) } |
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 |