-
Notifications
You must be signed in to change notification settings - Fork 0
/
orderedSinglyLinkedList.c
122 lines (105 loc) · 2.96 KB
/
orderedSinglyLinkedList.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
#include <stdio.h>
#include <stdlib.h>
// Node structure for the linked list
struct Node {
int data;
struct Node *next;
};
// Global variable for the header node
struct Node *header = NULL;
// Function to create a new node with given data
struct Node* getNode(int value) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// Function to free a node from memory
void freeNode(struct Node *node) {
free(node);
}
// Function to insert a node in an ordered manner
void insert(int value) {
struct Node *newNode = getNode(value);
if (header == NULL || header->data >= value) {
newNode->next = header;
header = newNode;
} else {
struct Node *current = header;
while (current->next != NULL && current->next->data < value) {
current = current->next;
}
newNode->next = current->next; //2->4->6->8 5 current=4 current->next->data=6
current->next = newNode; //if you're trying to insert A after B
// A->next = B->next
// B->next=A
}
}
// Function to delete a node with given data
void deleteNode(int value) {
if (header == NULL) {
printf("List is empty. Cannot delete.\n");
return;
}
struct Node *temp = header;
struct Node *prev = NULL;
if (temp->data == value) {
header = temp->next;
freeNode(temp);
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Element not found in the list.\n");
return;
}
prev->next = temp->next;
freeNode(temp);
}
// Function to display the linked list
void display() {
struct Node *current = header;
printf("Linked List: ");
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
// Main function to demonstrate the operations
int main() {
int choice, value;
while (1) {
printf("\nOperations on Ordered Singly Linked List:\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
insert(value);
break;
case 2:
printf("Enter value to delete: ");
scanf("%d", &value);
deleteNode(value);
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}