File tree Expand file tree Collapse file tree 1 file changed +107
-0
lines changed
algorithms/data-structures/stack Expand file tree Collapse file tree 1 file changed +107
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < cstdio>
3
+
4
+ using namespace std ;
5
+
6
+ // - Global Variable (came from main)!
7
+ struct Node *top = NULL ;
8
+
9
+ struct Node {
10
+ int data;
11
+ struct Node *next;
12
+ };
13
+
14
+ void linkedlistTraversal (struct Node * ptr){
15
+ while (ptr!=NULL ){
16
+ printf (" Element: %d\n " , ptr->data );
17
+ ptr = ptr->next ;
18
+ }
19
+ }
20
+
21
+ int isEmpty (struct Node * top){
22
+ if (top == NULL ){
23
+ return 1 ;
24
+ }
25
+ return 0 ;
26
+ }
27
+
28
+ int isFull (struct Node * top){
29
+ struct Node * n = (struct Node *) malloc (sizeof (struct Node ));
30
+ if (n == NULL ){
31
+ return 1 ;
32
+ }
33
+ return 0 ;
34
+ }
35
+
36
+ struct Node * push (struct Node * top, int data){
37
+ if (isFull (top)){
38
+ printf (" Stack Overflow!\n " );
39
+ }
40
+ else {
41
+ struct Node * n = (struct Node *) malloc (sizeof (struct Node ));
42
+ n->data = data;
43
+ n->next = top;
44
+ top = n;
45
+ return top;
46
+ }
47
+ }
48
+
49
+ int pop (struct Node * tp){
50
+ if (isEmpty (tp)){
51
+ printf (" Stack Underflow!" );
52
+ }
53
+ else {
54
+ struct Node * n = tp;
55
+ top = (tp)->next ;
56
+ int x = n->data ;
57
+ free (n);
58
+ return x;
59
+ }
60
+ }
61
+
62
+ int peek (int pos){
63
+ struct Node * ptr = top;
64
+ for (int i = 0 ; (i < pos-1 && ptr!=NULL ); i++)
65
+ {
66
+ ptr = ptr->next ;
67
+ }
68
+ if (ptr!=NULL ){
69
+ return ptr->data ;
70
+ }
71
+ else {
72
+ return -1 ; // assuming there's no -ve element in stack
73
+ }
74
+ }
75
+
76
+ int stackTop (struct Node * top){
77
+ return top->data ;
78
+ }
79
+
80
+ int stackBottom (struct Node * top){
81
+ struct Node * p = top;
82
+ while (p->next !=NULL ){
83
+ p = p->next ;
84
+ }
85
+ return p->data ;
86
+ }
87
+
88
+ int main ()
89
+ {
90
+ top = push (top, 69 );
91
+ top = push (top, 10 );
92
+ top = push (top, 8 );
93
+ top = push (top, 7 );
94
+ linkedlistTraversal (top);
95
+
96
+ for (int i = 1 ; i <= 4 ; i++)
97
+ {
98
+ printf (" The element at position %d is %d\n " ,i,peek (i));
99
+ }
100
+
101
+ // printf("The top most element in stack is %d\n",stackTop(top));
102
+ printf (" The bottom most element in stack is %d\n " ,stackBottom (top));
103
+
104
+
105
+
106
+ return 0 ;
107
+ }
You can’t perform that action at this time.
0 commit comments