-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathWithLinkedList.c
116 lines (97 loc) · 2.4 KB
/
WithLinkedList.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct list {
int data;
struct list *next;
}STACK;
// GLOBAL VARIABLES
STACK *sp = NULL; // stack pointer , shows the place for insertion and deletion
int counter = 0; // Stack size
void push(int data) { // Insertion function
STACK *temp = (STACK *)malloc(sizeof(STACK)); // Creating a new node and allocating memory to push stack
if (temp == NULL) {
printf("\nError, Could not allocate memory...\n");
}
else {
temp->data = data;
temp->next = sp;
sp = temp; // Stack pointer always shows the last inserted node
counter++;
printf("\nData inserted to the stack.\n\n");
}
}
int pop() { // Deletion function
STACK *temp; // temprorary stack pointer
int data; // to keep data
if (sp == NULL) { // Checks the stack
printf("\nStack is empty.Could not retrieve the data.\n\n");
return -1;
}
else {
temp = sp;
data = sp->data;
sp = sp->next; // Updates pointer
free(temp); // Deleted node from memory...
return data;
}
}
void reset() { // Reset function
STACK *temp; // temprorary pointer for free function
while (sp != NULL) {
temp = sp;
sp = sp->next;
free(temp);
}
printf("\nStack is empty now.\n\n");
}
STACK *top() { // Returns the adress of last element inserted
return sp;
}
int size() { //Shows the number of elements stored
return counter;
}
void isEmpty() { // Checks the stack whether it is empty or not . If it is , it returns 1 other wise it returns 0.
if (sp == NULL) {
printf("\nStack is empty.\n");
}
else
printf("\nStack is not empty. %d elements are stored.\n\n", counter);
}
int main() {
int choice;
int value;
int temp; // to keep poped data to display
while (1) {
printf("1-Push\n2-Pop\n3-Reset\n4-Top\n5-Size\n6-isEmpty\n7-Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value for insertion : ");
scanf("%d", &value);
push(value);
break;
case 2:
temp = pop();
if (temp != -1) {
printf("\nData -> %d \n\n", temp);
}
break;
case 3:
reset();
break;
case 4:
printf("\nThe last element is %d \n\n", top());
break;
case 5:
printf("\nThe number of elements stored -> %d \n\n\n", size());
break;
case 6:
isEmpty();
break;
case 7:
exit(0);
}
}
return 0;
}