Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd60f836

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 parentdda712c commitd60f836

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

‎DataStructures/Stacks/StackOfLinkedList.java

Lines changed: 21 additions & 16 deletions
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
classLinkedListStack {
5250

5351
Nodehead =null;
54-
intsize =0;
5552

5653
publicvoidpush(intx) {
5754
Noden =newNode(x);
58-
if (getSize() ==0) {
55+
if (head ==null) {
5956
head =n;
6057
}
6158
else {
6259
Nodetemp =head;
6360
n.next =temp;
6461
head =n;
6562
}
66-
size++;
6763
}
6864

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

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

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

8982
publicvoidprintStack() {
90-
9183
Nodetemp =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
publicbooleanisEmpty() {
102-
returngetSize() ==0;
98+
returnhead ==null;
10399
}
104100

105101
publicintgetSize() {
106-
returnsize;
102+
if(head ==null)
103+
return0;
104+
else {
105+
intsize =1;
106+
Nodetemp =head;
107+
while(temp.next !=null) {
108+
temp =temp.next;
109+
size++;
110+
}
111+
returnsize;
112+
}
107113
}
108-
109114
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp