C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Insertion in doubly linked list at beginningAs in doubly linked list, each node of the list contain double pointers therefore we have to maintain more number of pointers in doubly linked list as compare to singly linked list. There are two scenarios of inserting any element into doubly linked list. Either the list is empty or it contains at least one element. Perform the following steps to insert a node in doubly linked list at beginning.
ptr = (struct node *)malloc(sizeof(struct node));
ptr->next = NULL; ptr->prev=NULL; ptr->data=item; head=ptr;
ptr->next = head; head→prev=ptr; Since, the node being inserted is the first node of the list and therefore it must contain NULL in its prev pointer. Hence assign null to its previous part and make the head point to this node. ptr→prev =NULL head = ptr Algorithm :
  Write OVERFLOW C Function#include<stdio.h> #include<stdlib.h> void insertbeginning(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); insertbeginning(item); printf("\nPress 0 to insert more ?\n"); scanf("%d",&choice); }while(choice == 0); } void insertbeginning(int item) { struct node *ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { if(head==NULL) { ptr->next = NULL; ptr->prev=NULL; ptr->data=item; head=ptr; } else { ptr->data=item; ptr->prev=NULL; ptr->next = head; head->prev=ptr; head=ptr; } } } Output Enter the item which you want to insert? 12 Press 0 to insert more ? 0 Enter the item which you want to insert? 23 Press 0 to insert more ? 2 Output Enter the item which you want to insert? 12 Press 0 to insert more ? 2
Next TopicDoubly Linked List
|