forked from callmefarhan/DATA-STRUCTURE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EXP1b.txt
110 lines (103 loc) · 2.8 KB
/
EXP1b.txt
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
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* create(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the beginning
void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = create(data);
newNode->next = *head;
*head = newNode;
}
// Function to insert a node at the end
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = create(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to display the linked list
void display(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to delete a node
void delete(struct Node** head, int data) {
struct Node* temp = *head;
struct Node* prev = NULL;
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Element not found\n");
return;
}
prev->next = temp->next;
free(temp);
}
int main() {
struct Node* head = NULL;
int choice, data;
while (1) {
printf("\nLinked List Operations:\n");
printf("1. Insert at beginning\n");
printf("2. Insert at end\n");
printf("3. Delete\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter data: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter data to delete: ");
scanf("%d", &data);
delete(&head, data);
break;
case 4:
printf("Linked List: ");
display(head);
break;
case 5:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}