Skip to content

Commit b748b42

Browse files
committed
added peek() method and stack is now printed vertically
1 parent 595cc8f commit b748b42

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

Data Structures/Stacks/StackOfLinkedList.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public static void main(String[] args) {
1515
stack.push(2);
1616
stack.push(3);
1717
stack.push(4);
18+
stack.push(5);
1819

1920
stack.printStack();
2021

@@ -23,6 +24,8 @@ public static void main(String[] args) {
2324
stack.pop();
2425
stack.pop();
2526

27+
System.out.println("Top element of stack currently is: " + stack.peek());
28+
2629
}
2730

2831
}
@@ -75,12 +78,20 @@ public void pop() {
7578
System.out.println("Popped element is: " + temp.data);
7679
}
7780

81+
public int peek() {
82+
if (getSize() == 0) {
83+
return -1;
84+
}
85+
86+
return head.data;
87+
}
88+
7889
public void printStack() {
7990

8091
Node temp = head;
8192
System.out.println("Stack is printed as below: ");
8293
while (temp != null) {
83-
System.out.print(temp.data + " ");
94+
System.out.println(temp.data + " ");
8495
temp = temp.next;
8596
}
8697
System.out.println();
@@ -94,5 +105,5 @@ public boolean isEmpty() {
94105
public int getSize() {
95106
return size;
96107
}
97-
108+
98109
}

0 commit comments

Comments
 (0)