Skip to content

Commit 1d02cd4

Browse files
authored
Merge pull request TheAlgorithms#711 from ojasiiitd/patch-1
Updated StackOfLinkedList.java
2 parents dda712c + 2ea5340 commit 1d02cd4

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

DataStructures/Stacks/StackOfLinkedList.java

+25-24
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
/**
2-
*
32
* @author Varun Upadhyay (https://github.com/varunu28)
4-
*
53
*/
64

75
// An implementation of a Stack using a Linked List
@@ -25,9 +23,7 @@ public static void main(String[] args) {
2523
stack.pop();
2624

2725
System.out.println("Top element of stack currently is: " + stack.peek());
28-
2926
}
30-
3127
}
3228

3329
// A node class
@@ -44,66 +40,71 @@ public Node(int data) {
4440

4541
/**
4642
* A class which implements a stack using a linked list
47-
*
43+
* <p>
4844
* Contains all the stack methods : push, pop, printStack, isEmpty
4945
**/
5046

5147
class LinkedListStack {
5248

5349
Node head = null;
54-
int size = 0;
5550

5651
public void push(int x) {
5752
Node n = new Node(x);
58-
if (getSize() == 0) {
53+
if (head == null) {
5954
head = n;
60-
}
61-
else {
55+
} else {
6256
Node temp = head;
6357
n.next = temp;
6458
head = n;
6559
}
66-
size++;
6760
}
6861

6962
public void pop() {
70-
if (getSize() == 0) {
63+
if (head == null) {
7164
System.out.println("Empty stack. Nothing to pop");
7265
}
7366

7467
Node temp = head;
7568
head = head.next;
76-
size--;
77-
7869
System.out.println("Popped element is: " + temp.data);
7970
}
8071

8172
public int peek() {
82-
if (getSize() == 0) {
83-
return -1;
84-
}
85-
86-
return head.data;
73+
if (head == null) {
74+
return -1;
75+
}
76+
return head.data;
8777
}
8878

8979
public void printStack() {
90-
9180
Node temp = head;
9281
System.out.println("Stack is printed as below: ");
9382
while (temp != null) {
94-
System.out.println(temp.data + " ");
83+
if (temp.next == null) {
84+
System.out.print(temp.data);
85+
} else {
86+
System.out.print(temp.data + " -> ");
87+
}
9588
temp = temp.next;
9689
}
9790
System.out.println();
98-
9991
}
10092

10193
public boolean isEmpty() {
102-
return getSize() == 0;
94+
return head == null;
10395
}
10496

10597
public int getSize() {
106-
return size;
98+
if (head == null)
99+
return 0;
100+
else {
101+
int size = 1;
102+
Node temp = head;
103+
while (temp.next != null) {
104+
temp = temp.next;
105+
size++;
106+
}
107+
return size;
108+
}
107109
}
108-
109110
}

0 commit comments

Comments
 (0)