-
Notifications
You must be signed in to change notification settings - Fork 0
/
30_stack_linkedlist.c
88 lines (78 loc) · 1.71 KB
/
30_stack_linkedlist.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
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
void Traversal(struct Node *ptr){
while (ptr != NULL){
printf("Element is: %d\n", ptr -> data);
ptr = ptr -> next;
}
}
int isEmpty(struct Node * top){
if (top == NULL){
return 1;
}
else{
return 0;
}
}
int isFull(struct Node * top){
struct Node * ptr = (struct Node*)malloc(sizeof(struct Node));
if (ptr == NULL){
return 1;
}
else{
return 0;
}
}
struct Node *push (struct Node * top, int data){
if (!isFull(top)){
struct Node * ptr = (struct Node *)malloc(sizeof(struct Node));
ptr -> data = data;
ptr -> next = top;
top = ptr;
return top;
}
else{
printf("Stack overflow");
}
}
struct Node * pop (struct Node *top){
if(isEmpty(top)){
printf("Stack underflow");
}
else{
struct Node *ptr = top;
int value = top -> data;
top = top -> next;
printf("the popped value is %d \n", value);
free(ptr);
return top;
}
}
int peek(struct Node *top, int index){
int i = 0;
struct Node * ptr = top;
while (ptr -> next != NULL){
ptr = ptr -> next;
i = i + 1;
if (i == index){
return ptr -> data;
}
}
return -1;
}
int main(){
struct Node *top = NULL;
top = push(top, 5000);
top = push(top, 500);
top = push(top, 50);
top = push(top, 5);
// Traversal(top);
int qwerty = peek(top, 6);
printf("The value is %d", qwerty);
// Traversal(top);
return 0;
}