Skip to content

Commit 16973a6

Browse files
stacks
1 parent dbd5469 commit 16973a6

File tree

2 files changed

+107
-0
lines changed

2 files changed

+107
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package dsa.stack;
2+
3+
import java.util.ArrayList;
4+
5+
public class StackUsingArrayList {
6+
public static void main(String[] args) {
7+
Stack stack = new Stack();
8+
stack.push(1);
9+
stack.push(2);
10+
stack.push(3);
11+
stack.push(4);
12+
13+
while (!stack.isEmpty()) {
14+
System.out.println(stack.peek());
15+
stack.pop();
16+
}
17+
}
18+
19+
static class Stack {
20+
ArrayList<Integer> list = new ArrayList<>();
21+
22+
public void push(int data) {
23+
list.add(data);
24+
}
25+
26+
public boolean isEmpty() {
27+
return list.size() == 0;
28+
}
29+
30+
public int pop() {
31+
if (isEmpty()) {
32+
return -1;
33+
}
34+
int top = list.remove(list.size() - 1);
35+
return top;
36+
}
37+
38+
public int peek() {
39+
if (isEmpty()) {
40+
return -1;
41+
}
42+
return list.get(list.size() - 1);
43+
}
44+
}
45+
46+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package dsa.stack;
2+
3+
public class StackUsingLinkedList {
4+
public static void main(String[] args) {
5+
Stack.push(1);
6+
Stack.push(2);
7+
Stack.push(3);
8+
Stack.push(4);
9+
10+
while (!Stack.isEmpty()) {
11+
System.out.println(Stack.peek());
12+
Stack.pop();
13+
}
14+
}
15+
16+
private static class Node {
17+
int data;
18+
Node next;
19+
20+
Node(int data) {
21+
this.data = data;
22+
next = null;
23+
}
24+
}
25+
26+
static class Stack {
27+
public static Node head = null;
28+
29+
public static void push(int data) {
30+
Node newNode = new Node(data);
31+
32+
if (head == null) {
33+
head = newNode;
34+
return;
35+
}
36+
newNode.next = head;
37+
head = newNode;
38+
}
39+
40+
public static boolean isEmpty() {
41+
return head == null;
42+
}
43+
44+
public static int pop() {
45+
if (isEmpty()) {
46+
return -1;
47+
}
48+
Node top = head;
49+
head = head.next;
50+
return top.data;
51+
}
52+
53+
public static int peek() {
54+
if (isEmpty()) {
55+
return -1;
56+
}
57+
Node top = head;
58+
return top.data;
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)