-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathstack_linkedList.c
101 lines (90 loc) · 1.87 KB
/
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
89
90
91
92
93
94
95
96
97
98
99
100
101
// Implementation of a stack using linked list
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *top = NULL;
// Time complexity: O(1)
bool stack_empty()
{
return top == NULL;
}
// Time complexity: O(1)
void stack_push(int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (top)
newNode->next = top;
top = newNode;
}
// Time complexity: O(1)
int stack_pop()
{
if (stack_empty())
return -1;
int del = top->data;
struct Node *temp = top;
top = top->next;
free(temp);
return del;
}
// Time complexity: O(1)
int stack_peek()
{
if (stack_empty())
return -1;
return top->data;
}
void display()
{
if (stack_empty())
return;
for (struct Node *ptr = top; ptr; ptr = ptr->next)
printf("%d ", ptr->data);
}
int main()
{
int ch;
do
{
printf("\n\nEnter choice\n");
printf("1.Push");
printf("\n2.Pop");
printf("\n3.Peek");
printf("\n4.Display Stack\n");
scanf("%d", &ch);
int data, del, getTop;
switch (ch)
{
case 1:
printf("\nEnter data to insert\n");
scanf("%d", &data);
stack_push(data);
break;
case 2:
del = stack_pop();
if (del == -1)
printf("\nStack Empty");
else
printf("\nPopped: %d", del);
break;
case 3:
getTop = stack_peek();
if (getTop == -1)
printf("\nStack Empty");
else
printf("\nElement at top: %d", getTop);
break;
case 4:
printf("\nStack: ");
display();
}
} while (ch < 5);
return 0;
}