Skip to content

Commit b4649e5

Browse files
authored
Update Stack.java
Here's a code for a singly linkedlist. It's my first time contributing to an opensource for hacktoberfest.Apologies for any mistakes! Gonna make it better the next time! :)
1 parent 4a03f42 commit b4649e5

File tree

1 file changed

+97
-0
lines changed
  • src/main/java/com/thealgorithms/datastructures/stacks

1 file changed

+97
-0
lines changed

src/main/java/com/thealgorithms/datastructures/stacks/Stack.java

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,100 @@ public interface Stack<T> {
4949
*/
5050
void makeEmpty();
5151
}
52+
public class LinkedListStack<T> implements Stack<T> {
53+
54+
private Node<T> top = null;
55+
private int size = 0;
56+
57+
private static class Node<T> {
58+
T data;
59+
Node<T> next;
60+
61+
public Node(T data) {
62+
this.data = data;
63+
}
64+
}
65+
66+
@Override
67+
public void push(T value) {
68+
Node<T> newNode = new Node<>(value);
69+
newNode.next = top;
70+
top = newNode;
71+
size++;
72+
}
73+
74+
@Override
75+
public T pop() {
76+
if (isEmpty()) {
77+
throw new IllegalStateException("Stack is empty");
78+
}
79+
T value = top.data;
80+
top = top.next;
81+
size--;
82+
return value;
83+
}
84+
85+
@Override
86+
public T peek() {
87+
if (isEmpty()) {
88+
throw new IllegalStateException("Stack is empty");
89+
}
90+
return top.data;
91+
}
92+
93+
@Override
94+
public boolean isEmpty() {
95+
return top == null;
96+
}
97+
98+
@Override
99+
public int size() {
100+
return size;
101+
}
102+
103+
@Override
104+
public void makeEmpty() {
105+
top = null;
106+
size = 0;
107+
}
108+
109+
public void display() {
110+
if (isEmpty()) {
111+
System.out.println("Stack is empty.");
112+
} else {
113+
Node<T> temp = top;
114+
System.out.print("Stack: ");
115+
while (temp != null) {
116+
System.out.print(temp.data + " ");
117+
temp = temp.next;
118+
}
119+
System.out.println();
120+
}
121+
}
122+
123+
// Main method
124+
public static void main(String[] args) {
125+
LinkedListStack<Integer> stack = new LinkedListStack<>();
126+
System.out.println("Pushing elements onto the stack:");
127+
stack.push(10);
128+
stack.push(20);
129+
stack.push(30);
130+
stack.display();
131+
132+
System.out.println("\nPopped an element from the stack:");
133+
System.out.println(stack.pop());
134+
stack.display();
135+
136+
System.out.println("\nPeeking at the top element: " + stack.peek());
137+
System.out.println( stack.size());
138+
139+
System.out.println("\nPushed element 100 onto the stack:");
140+
stack.push(100);
141+
stack.display();
142+
143+
System.out.println("\nMaking the stack empty:");
144+
stack.makeEmpty();
145+
stack.display();
146+
}
147+
}
148+

0 commit comments

Comments
 (0)