1. Build a double linked list with 5 in the first node following the instructions: Insert a node with 3 at the top of the list Insert a node with 10 at the bottom of the list Insert a node with 7 between nodes with 5 and 10 2. Start deleting nodes from the list in the following order; Delete the node with 7 Delete the node with 3 Delete the node with 10 3. Print the resulting list forward and backwards. write your statements in C.
code: doublyLinkedList.c
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next, *prev;
}Node;
void displayList(Node *head){
Node *p = head, *r, *q;
r = q = p;
printf("Forward->\n");
while(p){
printf("%d, ",p->data);
r=p;
p = p->next;
}
printf("\n<-Backward\n");
while(r){
printf("%d, ", r->data);
r= r->prev;
}
printf("\n");
}
Node * createNode(int data){
Node * p = (Node *)malloc(sizeof(Node));
p->data = data;
p->next = NULL;
p->prev = NULL;
return p;
}
Node * addNodeToList(Node *head, int data){
Node *p, *q, *r;
q = createNode(data);
if(head==NULL){
head = q;
return head;
}
if(head->next==NULL){
if(head->data > data){
q->next = head;
q->next->prev = q;
head = q;
}
else{
head->next = q;
q->prev = head;
}
return head;
}
p = head;
while(p && p->data < data){
r = p;
p = p->next;
}
if(p==NULL){
r->next = q;
q->prev = r;
}
else{
r->next = q;
q->next = p;
q->prev = r;
p->prev = q;
}
return head;
}
Node * deleteNodeFromList(Node *head, int key){
Node *p, *r;
if(head==NULL){
return head;
}
if(head->next==NULL && head->data==key){
p = head;
free(p);
head = NULL;
return head;
}
if(head->data==key && head->next!=NULL){
p = head;
head = p->next;
head->prev = NULL;
free(p);
return head;
}
p = head;
while(p && p->data != key){
r = p;
p = p->next;
}
if(p==NULL){
return ;
}
else{
if(p->next==NULL){
r->next = NULL;
}
else{
p->next->prev = r;
r->next = p->next;
}
free(p);
}
return head;
}
int main(void){
Node *list = NULL;
list = addNodeToList(list, 5);
list = addNodeToList(list, 3);
list = addNodeToList(list, 10);
list = addNodeToList(list, 7);
list = deleteNodeFromList(list, 7);
list = deleteNodeFromList(list, 3);
list = deleteNodeFromList(list, 10);
displayList(list);
return 0;
}
output:
Get Answers For Free
Most questions answered within 1 hours.