-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList7.c
124 lines (111 loc) · 2.69 KB
/
LinkedList7.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
123
124
/*Implement Stack Using Linked List*/
#include <stdio.h>
#include <stdlib.h>
// Define the structure of a node in the stack
struct Node
{
int data;
struct Node *next;
};
// Function to create a new node
struct Node *newNode(int data)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
// Structure to represent the stack
struct Stack
{
struct Node *top;
};
// Function to initialize the stack
struct Stack *initialize()
{
struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
stack->top = NULL;
return stack;
}
// Function to check if the stack is empty
int isEmpty(struct Stack *stack)
{
return (stack->top == NULL);
}
// Function to push an element onto the stack
void push(struct Stack *stack, int data)
{
struct Node *node = newNode(data);
node->next = stack->top;
stack->top = node;
printf("%d pushed to stack.\n", data);
}
// Function to pop an element from the stack
int pop(struct Stack *stack)
{
if (isEmpty(stack))
{
printf("Stack is empty.\n");
return -1;
}
struct Node *temp = stack->top;
int popped = temp->data;
stack->top = stack->top->next;
free(temp);
return popped;
}
// Function to traverse and display elements of the stack
void traverse(struct Stack *stack)
{
if (isEmpty(stack))
{
printf("Stack is empty.\n");
return;
}
printf("Elements of the stack are: ");
struct Node *current = stack->top;
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main()
{
struct Stack *stack = initialize();
int choice, element;
do
{
printf("\nStack Operations Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Traverse\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter element to push: ");
scanf("%d", &element);
push(stack, element);
break;
case 2:
element = pop(stack);
if (element != -1)
printf("Popped element: %d\n", element);
break;
case 3:
traverse(stack);
break;
case 4:
printf("Exiting...\n");
exit(0);
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (1);
return 0;
}