Linked Lists Linked Representation of an Integer Stack

J.E.D.I.

3.3.6 Linked Lists

Before implementing the linked representation of stacks. Let’s first study how to create linked representation. In particular, we’ll be looking at linked lists. The linked list is a dynamic structure as opposed to the array, which is a static structure. This means that the linked list can grow and shrink in size depending on the need of the user. A linked list is defined as a collection of nodes, each of which consists of some data and a link or a pointer to the next node in the list. The figure below shows how a node looks like. Figure 3.3: A node Here is an example of a non-empty linked list with three nodes. Figure 3.4: A non-empty linked list with three nodes Here is how the node class is implemented. This class can be used to create linked lists. class Node { int data; integer data contained in the node Node nextNode; the next node in the list } class TestNode { public static void mainString args[] { Node emptyList = null; create an empty list head points to 1st node in the list Node head = new Node; initialize 1st node in the list head.data = 5; head.nextNode = new Node; head.nextNode.data = 10; null marks the end of the list head.nextNode.nextNode = null; print elements of the list Node currNode = head; while currNode = null { System.out.printlncurrNode.data; currNode = currNode.nextNode; } } } Introduction to Programming II Page 49 J.E.D.I. Here is a trace of TestNodes main method. Figure 3.5: Trace of TestNode Introduction to Programming II Page 50 J.E.D.I.

3.3.7 Linked Representation of an Integer Stack

Now that you’ve learned about linked list. You’re now ready to apply what you’ve learned to implement the linked representation of a stack. class DynamicIntStack{ private IntStackNode top; head or top of the stack class IntStackNode { node class int data; IntStackNode next; IntStackNodeint n { data = n; next = null; } } void pushint n{ no need to check for overflow IntStackNode node = new IntStackNoden; node.next = top; top = node; } int pop { if isEmpty { return -1; may throw a user-defined exception } else { int n = top.data; top = top.next; return n; } } boolean isEmpty{ return top == null; } public static void mainString args[] { DynamicIntStack myStack = new DynamicIntStack; myStack.push5; myStack.push10; print elements of the stack IntStackNode currNode = myStack.top; while currNode=null { System.out.printlncurrNode.data; currNode = currNode.next; } System.out.printlnmyStack.pop; System.out.printlnmyStack.pop; } } Here is the expected output of the code: Figure 3.6: Expected Output of DynamicStack Introduction to Programming II Page 51 J.E.D.I. Figure 3.7: Trace of DynamicStack Introduction to Programming II Page 52 J.E.D.I.

3.3.8 Java Collections