-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingLinkedList.java
More file actions
52 lines (48 loc) · 1.2 KB
/
StackUsingLinkedList.java
File metadata and controls
52 lines (48 loc) · 1.2 KB
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
public class StackUsingLinkedList {
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
ListNode head;
public void push(int val){
ListNode nn = new ListNode(val);
if(head == null){
head = nn;
return;
}
nn.next = head;
head = nn;
}
public int pop(){
int data = head.val;
if(head == null){
System.out.println("Stack underflow");
}
head = head.next;
return data;
}
public int peek(){
return head.val;
}
public void printStack(){
ListNode temp = head;
while(temp != null){
System.out.println("|"+temp.val+"|");
temp = temp.next;
}
}
public static void main(String[] args) {
StackUsingLinkedList Stack = new StackUsingLinkedList();
Stack.push(1);
Stack.push(2);
Stack.push(3);
Stack.push(4);
Stack.printStack();
Stack.pop();
System.out.println();
Stack.printStack();
}
}