forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackOfLinkedList.java
135 lines (112 loc) · 2.64 KB
/
StackOfLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package DataStructures.Stacks;
import java.util.NoSuchElementException;
/** @author Varun Upadhyay (https://github.com/varunu28) */
// An implementation of a Stack using a Linked List
class StackOfLinkedList {
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack);
System.out.println("Size of stack currently is: " + stack.getSize());
assert stack.pop() == 5;
assert stack.pop() == 4;
System.out.println("Top element of stack currently is: " + stack.peek());
}
}
// A node class
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
/**
* A class which implements a stack using a linked list
*
* <p>Contains all the stack methods : push, pop, printStack, isEmpty
*/
class LinkedListStack {
/** Top of stack */
Node head;
/** Size of stack */
private int size;
/** Init properties */
public LinkedListStack() {
head = null;
size = 0;
}
/**
* Add element at top
*
* @param x to be added
* @return <tt>true</tt> if add successfully
*/
public boolean push(int x) {
Node newNode = new Node(x);
newNode.next = head;
head = newNode;
size++;
return true;
}
/**
* Pop element at top of stack
*
* @return element at top of stack
* @throws NoSuchElementException if stack is empty
*/
public int pop() {
if (size == 0) {
throw new NoSuchElementException("Empty stack. Nothing to pop");
}
Node destroy = head;
head = head.next;
int retValue = destroy.data;
destroy = null; // clear to let GC do it's work
size--;
return retValue;
}
/**
* Peek element at top of stack
*
* @return element at top of stack
* @throws NoSuchElementException if stack is empty
*/
public int peek() {
if (size == 0) {
throw new NoSuchElementException("Empty stack. Nothing to pop");
}
return head.data;
}
@Override
public String toString() {
Node cur = head;
StringBuilder builder = new StringBuilder();
while (cur != null) {
builder.append(cur.data).append("->");
cur = cur.next;
}
return builder.replace(builder.length() - 2, builder.length(), "").toString();
}
/**
* Check if stack is empty
*
* @return <tt>true</tt> if stack is empty, otherwise <tt>false</tt>
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Return size of stack
*
* @return size of stack
*/
public int getSize() {
return size;
}
}