-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp5.c
122 lines (105 loc) · 2.52 KB
/
exp5.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
117
118
119
120
121
122
//single link list
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *next;
} node;
node* createNode(int new_data) {
node *newnode;
newnode = (node*)malloc(sizeof(node));
if (!newnode) {
printf("Memory is not allocated ");
exit(0);
}
newnode->data = new_data;
newnode->next = NULL;
return newnode;
}
void insertNodeFromHead(node **head, int data_) {
node* newnode = createNode(data_);
newnode->next = *head;
*head = newnode;
}
void insertNodeFromEnd(node **head, int data_) {
node* newnode = createNode(data_);
if (*head == NULL) {
*head = newnode;
return;
}
node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newnode;
}
void insertNodeATSpecificPos(node **head, int data_, int pos) {
node* newnode = createNode(data_);
if (pos == 0) {
newnode->next = *head;
*head = newnode;
return;
}
node* temp = *head;
for (int i = 0; i < pos - 1; i++) {
temp = temp->next;
if (temp == NULL) {
printf("Position out of bounds\n");
return;
}
}
newnode->next = temp->next;
temp->next = newnode;
}
void deleteNode(node** head) {
if (*head == NULL) {
printf("Stack is empty\n");
return;
}
node* temp = *head;
*head = (*head)->next;
free(temp);
}
void push_at_beginning(node **stack, int data) {
insertNodeFromHead(stack, data);
}
void push_at_end(node **stack, int data) {
insertNodeFromEnd(stack, data);
}
void push_at_position(node **stack, int data, int pos) {
insertNodeATSpecificPos(stack, data, pos);
}
void pop(node **stack) {
if (*stack == NULL) {
printf("Underflow\n");
return;
}
deleteNode(stack);
}
void printStack(node *stack) {
node *x = stack;
while (x != NULL) {
printf("%d\t", x->data);
x = x->next;
}
printf("\n");
}
void peek(node *stack) {
if (stack != NULL) {
printf("Top: %d\n", stack->data);
} else {
printf("Stack is empty\n");
}
}
int main() {
node *head = NULL;
insertNodeFromHead(&head, 10);
insertNodeFromHead(&head, 20);
insertNodeFromEnd(&head, 30);
insertNodeATSpecificPos(&head, 25, 2);
printStack(head);
peek(head);
pop(&head);
printStack(head);
return 0;
}