DS-(I) Assignment 5: Set A- b)

b) Implement a list library (doublylist.h) for a doubly linked list. Create a linked list, reverse it and display reversed linked list.

Solution:
#include<stdio.h>
#include<stdlib.h>
#include"doublylist.h"
main()
{
  int ch,n;
  struct node *head=NULL;
  do
  {
    printf("\nMENU\n");
    printf("\n1.Create");
    printf("\n2.Display");
    printf("\n3.Reverse");
    printf("\n4.Exit\n");
    printf("\nEnter Ur Choice\n");
    scanf("%d",&ch);
    switch(ch)
    {
        case 1:
            printf("\nEnter The Number of Node You Want\n");
            scanf("%d",&n);
            head=create(head,n);
            break;
        case 2:
               printf("\nLinked list is :\n");
            display(head);
            break;
        case 3:
            head=reverseList(head);
            break;
        case 4:
               exit(0);
            break;
        default :printf("\nInvalid choice ");     
     }
   } while(ch!=4);
}

Library Function ( .h file )
NOTE: save file name as ' doublylist.h'.

#include<stdio.h>
#include<stdlib.h>
struct node
{
  int data;
  struct node *next;
  struct node *prev;
};
struct node *tail;
struct node* create(struct node *head, int n)
{
    struct node *newnode, *temp;
    int i;
    for(i=1;i<=n;i++)
    {
        newnode = (struct node*)malloc(sizeof(struct node));
        printf("\n Enter node %d: ",i);
        scanf("%d",&newnode->data);
        newnode->next = newnode->prev=NULL;
        if (head == NULL)
        {
            head=tail=newnode;
        }
        else
        {
            tail->next=newnode;
            newnode->prev=tail;
            tail=newnode;
        }
    }
    return head;
}
void display(struct node* head)
{
    struct node *temp;
    if(head==NULL)
        printf("\nCreate List First!");
    else
    {   
        for(temp=head;temp!=NULL;temp=temp->next)
        {
            printf("\t %d ->",temp->data);
        }
        printf("NULL");
    }
}
struct node *reverseList(struct node *head)
{
    struct node *current = head, *temp = NULL;  
    //Swap the previous and next pointers of each node to reverse the direction of the list  
    while(current != NULL) {  
        temp = current->next;  
        current->next = current->prev;  
        current->prev = temp;  
        current = current->prev;  
    }  
    //Swap the head and tail pointers.  
    temp = head;  
    head = tail;  
    tail = temp;
    return(head);
}

0 Comments:

Post a Comment