-
Notifications
You must be signed in to change notification settings - Fork 1
/
Stack.c
110 lines (92 loc) · 1.9 KB
/
Stack.c
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include<stdio.h>
#include<stdlib.h>
#include <stdbool.h>
//Global top node
struct Node* top = NULL;
//Node representation with data and reference to next node
struct Node
{
int data;
struct Node* next;
};
//Checks if the stack is empty
bool isEmpty(struct Node* top)
{
if(top==NULL)
{
return true;
}
return false;
}
//Returns the top element of the stack
int topElement(struct Node* top)
{
if(isEmpty(top))
{
return 0;
}
else
{
return top->data;
}
}
struct Node* push(struct Node* top, int x)
{
//Dynamic memory node creation
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = NULL;
//if stack empty make temp as the top
if(isEmpty(top))
{
top = temp;
}
//else make temp->next point to the top and make temp as new top
else
{
temp->next = top;
top = temp;
}
printf("%d\n",x);
return top;
}
void pop()
{
struct Node* temp;
//if stack is empty there are no elements to show
if(isEmpty(top))
{
printf("No elements to show stack underflow");
return;
}
//else make the top point the next of the top and free the memory
else
{
temp = top;
top = top->next;
free(temp);
}
}
void print(struct Node* temp)
{
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp = temp->next;
}
}
int main()
{
//inserting element into the stack
top = push(top,1);
top = push(top,2);
top = push(top,3);
top = push(top,4);
top = push(top,5);
//Poping element from the stack
pop();
//top element of the stack
printf("%d\n",topElement(top));
//Print the stack
print(top);
}