-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedliststack.c
More file actions
77 lines (58 loc) · 1.09 KB
/
linkedliststack.c
File metadata and controls
77 lines (58 loc) · 1.09 KB
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
#include<stdio.h>
#include<stdlib.h>
//push isEmpty pop peek
typedef struct Node{
int data;
struct Node *next;
} Node;
Node *top = NULL;
void push(int data){
Node *newnode = malloc(sizeof(Node));
if(newnode == NULL){
printf("error maximum heap size reached");
return;
}
newnode->data = data;
newnode->next = top;
top = newnode;
}
int isEmpty(){
if(top == NULL){
printf("Empty stack");
return 1;
} else {
return 0;
}
}
int pop(){
if(isEmpty()){
return -1;
}
int val = top->data;
Node *temp = top;
top = top->next;
free(temp);
return val;
}
int peek(){
if(isEmpty()){
return -1;
}
return top->data;
}
int main(){
// 1. Add some data
push(10);
push(20);
push(30);
// 2. See what's at the top
printf("Top element is: %d\n", peek());
// 3. Remove and print everything
printf("Popping elements:\n");
while (top != NULL) {
printf("%d ", pop());
}
// 4. Test the empty case
pop();
return 0;
}