File tree 1 file changed +25
-24
lines changed
1 file changed +25
-24
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
- *
3
2
* @author Varun Upadhyay (https://github.com/varunu28)
4
- *
5
3
*/
6
4
7
5
// An implementation of a Stack using a Linked List
@@ -25,9 +23,7 @@ public static void main(String[] args) {
25
23
stack .pop ();
26
24
27
25
System .out .println ("Top element of stack currently is: " + stack .peek ());
28
-
29
26
}
30
-
31
27
}
32
28
33
29
// A node class
@@ -44,66 +40,71 @@ public Node(int data) {
44
40
45
41
/**
46
42
* A class which implements a stack using a linked list
47
- *
43
+ * <p>
48
44
* Contains all the stack methods : push, pop, printStack, isEmpty
49
45
**/
50
46
51
47
class LinkedListStack {
52
48
53
49
Node head = null ;
54
- int size = 0 ;
55
50
56
51
public void push (int x ) {
57
52
Node n = new Node (x );
58
- if (getSize () == 0 ) {
53
+ if (head == null ) {
59
54
head = n ;
60
- }
61
- else {
55
+ } else {
62
56
Node temp = head ;
63
57
n .next = temp ;
64
58
head = n ;
65
59
}
66
- size ++;
67
60
}
68
61
69
62
public void pop () {
70
- if (getSize () == 0 ) {
63
+ if (head == null ) {
71
64
System .out .println ("Empty stack. Nothing to pop" );
72
65
}
73
66
74
67
Node temp = head ;
75
68
head = head .next ;
76
- size --;
77
-
78
69
System .out .println ("Popped element is: " + temp .data );
79
70
}
80
71
81
72
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 ;
87
77
}
88
78
89
79
public void printStack () {
90
-
91
80
Node temp = head ;
92
81
System .out .println ("Stack is printed as below: " );
93
82
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
+ }
95
88
temp = temp .next ;
96
89
}
97
90
System .out .println ();
98
-
99
91
}
100
92
101
93
public boolean isEmpty () {
102
- return getSize () == 0 ;
94
+ return head == null ;
103
95
}
104
96
105
97
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
+ }
107
109
}
108
-
109
110
}
You can’t perform that action at this time.
0 commit comments