Repository navigation
Expand file tree
/
Copy path2_StackLinkedList.c
More file actions
91 lines (81 loc) · 1.5 KB
/
Copy path2_StackLinkedList.c
File metadata and controls
91 lines (81 loc) · 1.5 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *head = NULL;
Node *createNode () {
Node *newNode = (Node*)malloc(sizeof(Node));
return newNode;
}
void printNode(Node *ptr) {
printf("%d->", ptr->data);
}
void traverse () {
Node *ptr = head;
printf("Stack: ");
while (ptr != NULL) {
printNode(ptr);
ptr = ptr->next;
}
printf("NULL\n");
}
void insertFront (int data) {
Node *newNode = createNode();
if (newNode == NULL) {
printf("ERROR: Memory insufficient\n");
return;
}
newNode->data = data;
newNode->next = head;
head = newNode;
printf("Pushed: %d\n", data);
}
void deleteFront () {
Node *toDelete;
if (head == NULL) {
printf("Stack is already empty\n");
return;
}
toDelete = head;
head = head->next;
printf("Popped: %d\n", toDelete->data);
free(toDelete);
}
void peek () {
if (head == NULL) {
printf("Stack is empty\n");
return;
}
printf("Peek: %d\n", head->data);
}
int main () {
int choice, item, position;
while (1) {
printf("\n1: Push\n2: Pop\n3: Peek\n4: Display\n0: Exit\nEnter choice: ");
scanf("%d", &choice);
switch (choice) {
case 0:
return 0;
case 1:
printf("Enter element: ");
scanf("%d", &item);
insertFront(item);
traverse();
break;
case 2:
deleteFront();
traverse();
break;
case 3:
peek();
break;
case 4:
traverse();
break;
default:
printf("ERROR: Invalid choice\n");
}
}
}