-
Notifications
You must be signed in to change notification settings - Fork 1
/
stacklinkedlist.c
64 lines (50 loc) · 1.03 KB
/
stacklinkedlist.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
// C program for linked list implementation of stack
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct StackNode{
int data;
struct StackNode* next;
};
typedef struct StackNode SNODE;
//creation of new node in stack
SNODE* newNode(int data){
SNODE* snode=(SNODE*)malloc(sizeof(SNODE));
snode->data=data;
snode->next=NULL;
return snode;
}
//check whether stack is empty
int isEmpty(SNODE *root){
return !root;
}
//add new node!
void push(SNODE** root, int data){
SNODE* snode=newNode(data);
snode->next = *root;
*root=snode;
printf("%d pushed to stack \n",data);
}
int pop(SNODE** root){
if(isEmpty(*root))
return INT_MIN;
SNODE* temp=*root;
*root=(*root)->next;
int popped=temp->data;
free(temp);
return popped;
}
int peek(SNODE* root){
if(isEmpty(root))
return INT_MIN;
return root->data;
}
int main(){
SNODE* root=NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(root));
return 0;
}