So keeping it all simple this is a post to present the code that implements the Stacks using Linked List.
Like in the Linked list (obviously) made to classes one for nodes and other one for implementation.
Node class
Like in the Linked list (obviously) made to classes one for nodes and other one for implementation.
Node class
1 2 3 4 5 6 7 8 9 10 11 12 | public class NodeClass { public int info; public NodeClass next; public NodeClass(int i){ this(i,null); } public NodeClass(int x, NodeClass n){ info = x; next = n; } } |
Then the implementation:
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 | public class StackWithLL { protected NodeClass head; public StackWithLL(){ head = null; } public boolean isEmpty(){ return head == null; } public void push(int x){ head = new NodeClass(x,head); } public int pop(){ int temp = head.info; head = head.next; return temp; } public int peek(){ return head.info; } public static void main(String[] args) { StackWithLL stk = new StackWithLL(); stk.push(23); stk.push(45); stk.push(278); System.out.println("head :"+stk.peek()); System.out.println("Pop this one from head :"+stk.pop()); System.out.println("New head :"+stk.peek()); }} |
That's It have fun.