From b748b42dfef1aa06d4d07299bbd9978195fc682f Mon Sep 17 00:00:00 2001 From: shubhamtewari Date: Mon, 9 Jul 2018 15:52:42 +0530 Subject: [PATCH] added peek() method and stack is now printed vertically --- Data Structures/Stacks/StackOfLinkedList.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Data Structures/Stacks/StackOfLinkedList.java b/Data Structures/Stacks/StackOfLinkedList.java index 8903e52f0e72..35052457fe1c 100644 --- a/Data Structures/Stacks/StackOfLinkedList.java +++ b/Data Structures/Stacks/StackOfLinkedList.java @@ -15,6 +15,7 @@ public static void main(String[] args) { stack.push(2); stack.push(3); stack.push(4); + stack.push(5); stack.printStack(); @@ -23,6 +24,8 @@ public static void main(String[] args) { stack.pop(); stack.pop(); + System.out.println("Top element of stack currently is: " + stack.peek()); + } } @@ -75,12 +78,20 @@ public void pop() { System.out.println("Popped element is: " + temp.data); } + public int peek() { + if (getSize() == 0) { + return -1; + } + + return head.data; + } + public void printStack() { Node temp = head; System.out.println("Stack is printed as below: "); while (temp != null) { - System.out.print(temp.data + " "); + System.out.println(temp.data + " "); temp = temp.next; } System.out.println(); @@ -94,5 +105,5 @@ public boolean isEmpty() { public int getSize() { return size; } - + }