C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Insertion in doubly linked list at the endIn order to insert a node in doubly linked list at the end, we must make sure whether the list is empty or it contains any element. Use the following steps in order to insert the node in doubly linked list at the end.
ptr = (struct node *) malloc(sizeof(struct node));
ptr->next = NULL; ptr->prev=NULL; ptr->data=item; head=ptr;
Temp = head; while (temp != NULL) { temp = temp → next; } the pointer temp point to the last node at the end of this while loop. Now, we just need to make a few pointer adjustments to insert the new node ptr to the list. First, make the next pointer of temp point to the new node being inserted i.e. ptr. temp→next =ptr; make the previous pointer of the node ptr point to the existing last node of the list i.e. temp. ptr → prev = temp; make the next pointer of the node ptr point to the null as it will be the new last node of the list. ptr → next = NULL Algorithm
 Write OVERFLOW [END OF LOOP] C Program#include<stdio.h> #include<stdlib.h> void insertlast(int); struct node { int data; struct node *next; struct node *prev; }; struct node *head; void main () { int choice,item; do { printf("\nEnter the item which you want to insert?\n"); scanf("%d",&item); insertlast(item); printf("\nPress 0 to insert more ?\n"); scanf("%d",&choice); }while(choice == 0); } void insertlast(int item) { struct node *ptr = (struct node *) malloc(sizeof(struct node)); struct node *temp; if(ptr == NULL) { printf("\nOVERFLOW"); } else { ptr->data=item; if(head == NULL) { ptr->next = NULL; ptr->prev = NULL; head = ptr; } else { temp = head; while(temp->next!=NULL) { temp = temp->next; } temp->next = ptr; ptr ->prev=temp; ptr->next = NULL; } printf("\nNode Inserted\n"); } } Output Enter the item which you want to insert? 12 Node Inserted Press 0 to insert more ? 2
Next TopicDoubly Linked List
|