Implementing a Stack using Linked List in Java
Stack is a first in last out, last in first out data structure. It’s like stacking plates. In the following stack implementation, it uses linked list to implement the stack. There is the push method for adding an object, and there is the pop method for popping an object off the stack, as well as some other methods such as peek, size, isEmpty.
public class MyStack{ private class Node { V v; Node next; public Node(V v) { this.v = v; } } private int size; private Node head; public MyStack() { size = 0; head = null; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void push(V v) { Node newNode = new Node(v); if (head == null) { head = newNode; } else { newNode.next = head; head = newNode; } size++; } public V pop() { if (head == null) return null; Node n = head; head = head.next; size--; return n.v; } public V peek() { if (head == null) return null; return head.v; } public static void main(String args[]) { MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.push(3); System.out.println("Expected size 3, Actual size: " + myStack.size()); Integer i = (Integer) myStack.pop(); System.out.println("Expected size 2, Actual size: " + myStack.size()); System.out.println("Expected popped value 3, Actual popped value: " + i); i = (Integer) myStack.pop(); System.out.println("Expected popped value 2, Actual popped value: " + i); i = (Integer) myStack.pop(); System.out.println("Expected popped value 1, Actual popped value: " + i); System.out.println("Expected size 0, Actual size: " + myStack.size()); myStack.push(1); myStack.push(2); myStack.push(3); i = (Integer) myStack.peek(); System.out.println("Expected size 3, Actual size: " + myStack.size()); System.out.println("Expected peeked value 3, Actual peeked value: " + i); } }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts