Skip to content

Commit d60f836

Browse files
authored
Updated StackOfLinkedList.java
I made the code shorter and less prone to mistakes by removing the "size" variable altogether from the LinkedList class. I found that after each push/pop operation, changing the value of size did make the code more efficient, but made it more prone to mistakes. So, for empty stack, a simple "head == null" was enough, which has been incorporated.
1 parent dda712c commit d60f836

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

DataStructures/Stacks/StackOfLinkedList.java

+21-16
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@ public static void main(String[] args) {
2525
stack.pop();
2626

2727
System.out.println("Top element of stack currently is: " + stack.peek());
28-
2928
}
30-
3129
}
3230

3331
// A node class
@@ -51,59 +49,66 @@ public Node(int data) {
5149
class LinkedListStack {
5250

5351
Node head = null;
54-
int size = 0;
5552

5653
public void push(int x) {
5754
Node n = new Node(x);
58-
if (getSize() == 0) {
55+
if (head == null) {
5956
head = n;
6057
}
6158
else {
6259
Node temp = head;
6360
n.next = temp;
6461
head = n;
6562
}
66-
size++;
6763
}
6864

6965
public void pop() {
70-
if (getSize() == 0) {
66+
if (head == null) {
7167
System.out.println("Empty stack. Nothing to pop");
7268
}
7369

7470
Node temp = head;
7571
head = head.next;
76-
size--;
77-
7872
System.out.println("Popped element is: " + temp.data);
7973
}
8074

8175
public int peek() {
82-
if (getSize() == 0) {
76+
if (head == null) {
8377
return -1;
8478
}
85-
8679
return head.data;
8780
}
8881

8982
public void printStack() {
90-
9183
Node temp = head;
9284
System.out.println("Stack is printed as below: ");
9385
while (temp != null) {
94-
System.out.println(temp.data + " ");
86+
if(temp.next == null) {
87+
System.out.print(temp.data);
88+
}
89+
else {
90+
System.out.print(temp.data + " -> ");
91+
}
9592
temp = temp.next;
9693
}
9794
System.out.println();
98-
9995
}
10096

10197
public boolean isEmpty() {
102-
return getSize() == 0;
98+
return head == null;
10399
}
104100

105101
public int getSize() {
106-
return size;
102+
if(head == null)
103+
return 0;
104+
else {
105+
int size = 1;
106+
Node temp = head;
107+
while(temp.next != null) {
108+
temp = temp.next;
109+
size++;
110+
}
111+
return size;
112+
}
107113
}
108-
109114
}

0 commit comments

Comments
 (0)