Skip to content

Commit 19579c4

Browse files
Create 1 Stack using LL.java
1 parent 1534a22 commit 19579c4

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

3 LinkedLists/1 Stack using LL.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package Stacks;
2+
import java.util.*;
3+
4+
public class LinkedListImplementation {
5+
ListNode head;
6+
int size;
7+
public static class ListNode{
8+
int val;
9+
ListNode next;
10+
public ListNode(){
11+
this.next = null;
12+
}
13+
public ListNode(int val){
14+
this.val = val;
15+
this.next = null;
16+
}
17+
}
18+
19+
public LinkedListImplementation(){
20+
head = new ListNode();
21+
size = 0;
22+
}
23+
24+
//O(1)
25+
//Insert at the beginning in a singly linked list
26+
public void push(int x){
27+
size++;
28+
ListNode newnode = new ListNode(x);
29+
newnode.next = head;
30+
head = newnode;
31+
System.out.println(x+" is pushed onto the stack");
32+
}
33+
34+
//O(1)
35+
//Delete from beginning of a linked list
36+
public int pop(){
37+
int ret = head.val;
38+
//Delete head
39+
head = head.next;
40+
size--;
41+
System.out.println(ret+"is popped from the stack");
42+
return ret;
43+
}
44+
45+
public int peek(){
46+
return head.val;
47+
}
48+
49+
public boolean isEmpty(){
50+
return (size==0);
51+
}
52+
53+
public int size(){
54+
return size;
55+
}
56+
57+
public static void main(String[] args) {
58+
LinkedListImplementation l = new LinkedListImplementation();
59+
l.push(4);
60+
l.push(5);
61+
System.out.println(l.peek());
62+
System.out.println(l.pop());
63+
System.out.println(l.size());
64+
System.out.println(l.isEmpty());
65+
}
66+
}

0 commit comments

Comments
 (0)