diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java index 35052457..7b744bcb 100644 --- a/DataStructures/Stacks/StackOfLinkedList.java +++ b/DataStructures/Stacks/StackOfLinkedList.java @@ -25,9 +25,7 @@ class StackOfLinkedList { stack.pop(); System.out.println("Top element of stack currently is: " + stack.peek()); - } - } // A node class @@ -51,11 +49,10 @@ class Node { class LinkedListStack { Node head = null; - int size = 0; public void push(int x) { Node n = new Node(x); - if (getSize() == 0) { + if (head == null) { head = n; } else { @@ -63,47 +60,55 @@ class LinkedListStack { n.next = temp; head = n; } - size++; } public void pop() { - if (getSize() == 0) { + if (head == null) { System.out.println("Empty stack. Nothing to pop"); } Node temp = head; head = head.next; - size--; - System.out.println("Popped element is: " + temp.data); } public int peek() { - if (getSize() == 0) { + if (head == null) { return -1; } - return head.data; } public void printStack() { - Node temp = head; System.out.println("Stack is printed as below: "); while (temp != null) { - System.out.println(temp.data + " "); + if(temp.next == null) { + System.out.print(temp.data); + } + else { + System.out.print(temp.data + " -> "); + } temp = temp.next; } System.out.println(); - } public boolean isEmpty() { - return getSize() == 0; + return head == null; } public int getSize() { - return size; + if(head == null) + return 0; + else { + int size = 1; + Node temp = head; + while(temp.next != null) { + temp = temp.next; + size++; + } + return size; + } } - }