File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments