Answered! Write a code snippet to insert( or remove) a data value from a doubly-linked list….

Write a code snippet to insert( or remove) a data value from a doubly-linked list.

Expert Answer

Here is code:

#include <iostream>
#include <stdlib.h> /* malloc, free, rand */
using namespace std;
/* a node of the doubly linked list */
struct node
{
int data;
struct node *next;
struct node *prev;
};

void deleteNode(struct node **refNode, struct node *deleteNode)
{
// base case
if(*refNode == NULL || deleteNode == NULL)
return;

// if the node is head node
if(*refNode == deleteNode)
*refNode = deleteNode->next;

// if the node is in middle
if(deleteNode->next != NULL)
deleteNode->next->prev = deleteNode->prev;

// change the prev node
if(deleteNode->prev != NULL)
deleteNode->prev->next = deleteNode->next;
return;
}

void push(struct node** refNode, int newData)
{
// allocate node
struct node* newNode = (struct node*) malloc(sizeof(struct node));

// put in the data
newNode->data = newData;

// set the previous node to null
newNode->prev = NULL;

// set the next node to refNode
newNode->next = (*refNode);

// set the previous data to new Naode
if((*refNode) != NULL)
(*refNode)->prev = newNode ;

// new head
(*refNode) = newNode;
}

void printList(struct node *node)
{
while(node!=NULL)
{
cout << node->data << ” “;
node = node->next;
}
}

int main()
{
struct node* head = NULL;
push(&head, 5);
push(&head, 6);
push(&head, 7);
push(&head, 11);
push(&head, 15);
push(&head, 20);

//Delete node
deleteNode(&head, head);
deleteNode(&head, head->next);
deleteNode(&head, head->next);

cout << “n Modified Linked list “;
printList(head);
}

Still stressed from student homework?
Get quality assistance from academic writers!