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

Commit1d02cd4

Browse files
authored
Merge pull requestTheAlgorithms#711 from ojasiiitd/patch-1
Updated StackOfLinkedList.java
2 parentsdda712c +2ea5340 commit1d02cd4

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

‎DataStructures/Stacks/StackOfLinkedList.java

Lines changed: 25 additions & 24 deletions
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
classLinkedListStack {
5248

5349
Nodehead =null;
54-
intsize =0;
5550

5651
publicvoidpush(intx) {
5752
Noden =newNode(x);
58-
if (getSize() ==0) {
53+
if (head ==null) {
5954
head =n;
60-
}
61-
else {
55+
}else {
6256
Nodetemp =head;
6357
n.next =temp;
6458
head =n;
6559
}
66-
size++;
6760
}
6861

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

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

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

8979
publicvoidprintStack() {
90-
9180
Nodetemp =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
publicbooleanisEmpty() {
102-
returngetSize() ==0;
94+
returnhead ==null;
10395
}
10496

10597
publicintgetSize() {
106-
returnsize;
98+
if (head ==null)
99+
return0;
100+
else {
101+
intsize =1;
102+
Nodetemp =head;
103+
while (temp.next !=null) {
104+
temp =temp.next;
105+
size++;
106+
}
107+
returnsize;
108+
}
107109
}
108-
109110
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp