Answer to Question #249188 in C for Amit

Question #249188

Create and reverse a doubly linked list.


1
Expert's answer
2021-10-11T06:57:07-0400




#include <stdio.h>
#include <stdlib.h>
 


struct doubleLinkedList
{
  int item;
  struct doubleLinkedList *nextNode;
  struct doubleLinkedList *prevNode;   
};
 
//Function that reverses the linked list
void reverse(struct doubleLinkedList **head)
{
     struct doubleLinkedList *tempNode = NULL; 
     struct doubleLinkedList *currentNode = *head;
      
    
     while (currentNode !=  NULL)
     {
       tempNode = currentNode->prevNode;
       currentNode->prevNode = currentNode->nextNode;
       currentNode->nextNode = tempNode;             
       currentNode = currentNode->prevNode;
     }     
      
     
     if(tempNode != NULL )
        *head = tempNode->prevNode;
}    
 
 
 
//Function to create double linked list
void push(struct doubleLinkedList** head, int data)
{
    
    struct doubleLinkedList* node = (struct doubleLinkedList*) malloc(sizeof(struct doubleLinkedList));
  
    
    node->item  = data;
     
    
    node->prevNode = NULL;
  
    
    node->nextNode = (*head);   
 
    
    if((*head) !=  NULL)
      (*head)->prevNode = node ;   
  
    
    (*head)    = node;
}
 
/* Function to print doubly linked list */
void printList(struct doubleLinkedList *node)
{
  while(node!=NULL)
  {
   printf("%d ", node->item);
   node = node->nextNode;
  }
}


int main()
{
  
  struct doubleLinkedList* node = NULL;
  
  
  push(&node, 1);
  push(&node, 2);
  push(&node, 3);
  push(&node, 4);
  
  printf("\n The Original Double Linked List ");
  printList(node);
  
  
  reverse(&node);
  
  printf("\n The Reversed Linked list ");
  printList(node);          
  
  getchar();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS