Develop pseudocode of following operations for Doubly Circular Linked List.
i) Insertion of a node at beginning.
ii) Insertion of a node at end.
iii) Deletion of first node.
iv) Deletion of last node.
#include <iostream>
using namespace std;
struct Node {
int d;
struct Node* next;
struct Node* prev;
};
void insert(struct Node** s, int value)
{
if (*s == NULL) {
struct Node* new_node = new Node;
new_node->d = value;
new_node->next = new_node->prev = new_node;
*s = new_node;
return;
}
Node* last = (*s)->prev;
struct Node* new_node = new Node;
new_node->d = value;
new_node->next = *s;
(*s)->prev = new_node;
new_node->prev = last;
last->next = new_node;
}
void deleteNode(struct Node** s, int key)
{
if (*s == NULL)
return;
struct Node *curr = *s, *prev_1 = NULL;
while (curr->d != key) {
if (curr->next == *s) {
printf("\nList doesn't have node with value = %d", key);
return;
}
prev_1 = curr;
curr = curr->next;
}
if (curr->next == *s && prev_1 == NULL) {
(*s) = NULL;
free(curr);
return;
}
if (curr == *s) {
prev_1 = (*s)->prev;
*s = (*s)->next;
prev_1->next = *s;
(*s)->prev = prev_1;
free(curr);
}
else if (curr->next == *s) {
prev_1->next = *s;
(*s)->prev = prev_1;
free(curr);
}
else {
struct Node* temp = curr->next;
prev_1->next = temp;
temp->prev = prev_1;
free(curr);
}
}
void display(struct Node* s)
{
struct Node* temp = s;
while (temp->next != s) {
printf("%d ", temp->d);
temp = temp->next;
}
printf("%d ", temp->d);
}
int main()
{
struct Node* s = NULL;
//Insertion of a node at beginning.
insert(&s, 4);
insert(&s, 5);
insert(&s, 6);
insert(&s, 7);
//Insertion of a node at end.
insert(&s, 8);
printf("Before Deletion: ");
display(s);
deleteNode(&s, 9);
printf("\nAfter Deletion: ");
display(s);
//Deletion of first node.
deleteNode(&s, 4);
printf("\nAfter Deleting %d: ", 4);
display(s);
//Deletion of last node
deleteNode(&s, 8);
printf("\nAfter Deleting %d: ", 8);
display(s);
deleteNode(&s, 6);
printf("\nAfter Deleting %d: ", 6);
display(s);
return 0;
}
Comments
Leave a comment