top of page
A doubly linked list is a data structure in which each node contains not only a data element but also two pointers, one pointing to the previous node and one pointing to the next node in the list. This allows for efficient traversal in both directions, as well as easy insertion and deletion of nodes at any position in the list.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct DoublyLinkedList {
struct Node* head;
struct Node* tail;
int count;
};
struct Node* create_node(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->prev = NULL;
node->next = NULL;
return node;
}
struct DoublyLinkedList* create_list() {
struct DoublyLinkedList* list = (struct DoublyLinkedList*)malloc(sizeof(struct DoublyLinkedList));
list->head = NULL;
list->tail = NULL;
list->count = 0;
return list;
}
void append(struct DoublyLinkedList* list, int data) {
struct Node* node = create_node(data);
if (list->head == NULL) {
list->head = node;
list->tail = node;
} else {
node->prev = list->tail;
list->tail->next = node;
list->tail = node;
}
list->count++;
}
int remove_node(struct DoublyLinkedList* list, int data) {
struct Node* current = list->head;
while (current != NULL) {
if (current->data == data) {
if (current == list->head && current == list->tail) {
list->head = NULL;
list->tail = NULL;
} else if (current == list->head) {
list->head = current->next;
list->head->prev = NULL;
} else if (current == list->tail) {
list->tail = current->prev;
list->tail->next = NULL;
} else {
current->prev->next = current->next;
current->next->prev = current->prev;
}
free(current);
list->count--;
return 1;
}
current = current->next;
}
return 0;
}
void print_list(struct DoublyLinkedList* list) {
struct Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct DoublyLinkedList* list = create_list();
append(list, 1);
append(list, 2);
append(list, 3);
print_list(list); // output: 1 2 3
remove_node(list, 2);
print_list(list); // output: 1 3
return 0;
}
0 views0 comments
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head,*newnode,*prevnode,*nextnode;
int choice;
void main() {
printf("\n----Insertion At Beginning----");
struct node *temp;
do
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("\nEnter data : ");
scanf("%d",&newnode->data);
newnode->next=head;
head=newnode;
printf("\nEnter your choice : (0/1) ");
scanf("%d",&choice);
}while(choice);
temp=head;
printf("\n");
while(temp!=0)
{
printf("--%d",temp->data);
temp=temp->next;
}
printf("\n\n");
prevnode=0,temp=nextnode=head;
while(nextnode!=0)
{
nextnode=nextnode->next;
temp->next=prevnode;
prevnode=temp;
temp=nextnode;
}
head=prevnode;
temp=head;
printf("\n");
while(temp!=0)
{
printf("--%d",temp->data);
temp=temp->next;
}
}
1 view0 comments
bottom of page