-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.c
60 lines (51 loc) · 981 Bytes
/
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
#include <stdio.h>
#include <stdlib.h>
typedef struct stackNode
{
int data;
struct stackNode *next;
}stackNode;
stackNode *newNode(int data)
{
stackNode *tempStack=(stackNode *)malloc(sizeof(stackNode));
tempStack->data=data;
tempStack->next=NULL;
return tempStack;
}
int isEmpty(stackNode* top)
{
return !top;
}
void push(stackNode **top,int data)
{
stackNode *stack=newNode(data);
stack->next=*top;
*top=stack;
printf("%d pushed to stack\n",data);
}
int pop(stackNode** top)
{
if(isEmpty(*top))
return -1;
stackNode *temp=*top;
*top=(*top)->next;
int popped=temp->data;
free(temp);
return popped;
}
int peek(stackNode *top)
{
if(isEmpty(top))
return -1;
return top->data;
}
int main()
{
stackNode *top=NULL;
push(&top,10);
push(&top,20);
push(&top,30);
printf("%d popped from stack\n",pop(&top));
printf("Top element is %d\n",peek(top));
return 0;
}