Skip to content

Commit 35769b9

Browse files
Added Data Structure & Algorithm in C-Programming πŸ‘¨β€πŸ’»
1 parent daf5a5a commit 35769b9

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct Node {
5+
int data;
6+
struct Node* next;
7+
struct Node* prev;
8+
};
9+
10+
struct Node* head = NULL;
11+
12+
struct Node* createNode(int data) {
13+
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
14+
if (!newNode) {
15+
printf("Memory allocation failed.\n");
16+
exit(1);
17+
}
18+
newNode->data = data;
19+
newNode->next = newNode->prev = NULL;
20+
return newNode;
21+
}
22+
23+
void insertAtLast(int data) {
24+
struct Node* newNode = createNode(data);
25+
26+
if (head == NULL) {
27+
head = newNode;
28+
head->next = head->prev = newNode;
29+
} else {
30+
newNode->prev = head->prev;
31+
newNode->next = head;
32+
head->prev->next = newNode;
33+
head->prev = newNode;
34+
}
35+
}
36+
37+
void deleteFromLast() {
38+
if (head == NULL) {
39+
printf("List is empty.\n");
40+
return;
41+
}
42+
43+
if (head->next == head) { // Only one node in the list
44+
free(head);
45+
head = NULL;
46+
} else {
47+
struct Node* temp = head->prev;
48+
head->prev = temp->prev;
49+
temp->prev->next = head;
50+
free(temp);
51+
}
52+
}
53+
54+
void displayList() {
55+
if (head == NULL) {
56+
printf("List is empty.\n");
57+
return;
58+
}
59+
60+
struct Node* current = head;
61+
printf("Circular Doubly Linked List: ");
62+
do {
63+
printf("%d ", current->data);
64+
current = current->next;
65+
} while (current != head);
66+
printf("\n");
67+
}
68+
69+
int main() {
70+
insertAtLast(100);
71+
insertAtLast(200);
72+
insertAtLast(300);
73+
74+
printf("Before deletion:\n");
75+
displayList();
76+
77+
deleteFromLast();
78+
79+
printf("After deletion from last:\n");
80+
displayList();
81+
82+
return 0;
83+
}
84+

0 commit comments

Comments
Β (0)