File tree 1 file changed +98
-0
lines changed 1 file changed +98
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ *
3
+ * @author Varun Upadhyay (https://github.com/varunu28)
4
+ *
5
+ */
6
+
7
+ // An implementation of a Stack using a Linked List
8
+
9
+ class StackOfLinkedList {
10
+
11
+ public static void main (String [] args ) {
12
+
13
+ LinkedListStack stack = new LinkedListStack ();
14
+ stack .push (1 );
15
+ stack .push (2 );
16
+ stack .push (3 );
17
+ stack .push (4 );
18
+
19
+ stack .printStack ();
20
+
21
+ System .out .println ("Size of stack currently is: " + stack .getSize ());
22
+
23
+ stack .pop ();
24
+ stack .pop ();
25
+
26
+ }
27
+
28
+ }
29
+
30
+ // A node class
31
+
32
+ class Node {
33
+ public int data ;
34
+ public Node next ;
35
+
36
+ public Node (int data ) {
37
+ this .data = data ;
38
+ this .next = null ;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * A class which implements a stack using a linked list
44
+ *
45
+ * Contains all the stack methods : push, pop, printStack, isEmpty
46
+ **/
47
+
48
+ class LinkedListStack {
49
+
50
+ Node head = null ;
51
+ int size = 0 ;
52
+
53
+ public void push (int x ) {
54
+ Node n = new Node (x );
55
+ if (getSize () == 0 ) {
56
+ head = n ;
57
+ }
58
+ else {
59
+ Node temp = head ;
60
+ n .next = temp ;
61
+ head = n ;
62
+ }
63
+ size ++;
64
+ }
65
+
66
+ public void pop () {
67
+ if (getSize () == 0 ) {
68
+ System .out .println ("Empty stack. Nothing to pop" );
69
+ }
70
+
71
+ Node temp = head ;
72
+ head = head .next ;
73
+ size --;
74
+
75
+ System .out .println ("Popped element is: " + temp .data );
76
+ }
77
+
78
+ public void printStack () {
79
+
80
+ Node temp = head ;
81
+ System .out .println ("Stack is printed as below: " );
82
+ while (temp != null ) {
83
+ System .out .print (temp .data + " " );
84
+ temp = temp .next ;
85
+ }
86
+ System .out .println ();
87
+
88
+ }
89
+
90
+ public boolean isEmpty () {
91
+ return getSize () == 0 ;
92
+ }
93
+
94
+ public int getSize () {
95
+ return size ;
96
+ }
97
+
98
+ }
You can’t perform that action at this time.
0 commit comments