Tuesday, 29 August 2017

C Program To Reverse Linked List

Example Program To Reverse Singly Linked List:

Simple Logic 

struct node{
int data;
int next;
}
int Reverselist(int *n)
{
   struct node *t,temp=NULL;
   
  while(t!=NULL)
  {
        t=head->next;
       head->next=temp;
       temp=head;
      head->next=t;
   }
  return temp;  //reversed list is returned 
}



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

  struct sllNode {

        int data;
        struct sllNode *nextPtr;
  };

  struct sllNode *front = NULL;

  struct sllNode *rear = NULL;

  /*

    * creates Node and fill the given data
    */
  struct sllNode * createNode(int data) {
        struct sllNode *ptr = (struct sllNode *) malloc(sizeof (struct sllNode));
        ptr->data = data;
        ptr->nextPtr = NULL;
        return ptr;
  }

  /* inserting node at the end of the list */

  void insertionOp(int data) {
        struct sllNode *ptr =  createNode(data);
        if (rear == NULL) {
                front = ptr;
                rear = ptr;
        }
        rear->nextPtr = ptr;
        rear = ptr;
  }
  /* delete all nodes in the list */
  void deleteList() {
        struct sllNode *ptr;
        ptr = front;
        while (ptr){
                front = ptr->nextPtr;
                free(ptr);
                ptr = front;
        }
  }

  /* traverse the list and print the data in each node */
  int walkList() {
        struct sllNode *ptr;
        int i = 0;
        ptr = front;
        while (ptr) {
                printf("%d ", ptr->data);
                ptr = ptr->nextPtr;
                i++;
        }
        return (i);
  }

  /* reverse the linked list */
  void reverseList() {
        struct sllNode *xPtr, *yPtr, *zPtr;
        yPtr = zPtr = NULL;
        xPtr = front;
        while (xPtr) {
                zPtr = yPtr;
                yPtr = xPtr;
                xPtr = xPtr->nextPtr;
                yPtr->nextPtr = zPtr;
        }
        front = yPtr;
        return;
  }
  int main (int argc, char *argv[]) {
        int data, i, n;
        FILE *fp;

        fp = fopen(argv[1], "r");
        if (!fp) {
                printf("Unable to open the file\n");
                exit(0);
        }
        /* scan the inputs from the file & insert it into the list */
        while (fscanf(fp, "%d", &data) != EOF) {
                insertionOp(data);
        }
        printf("\nData in Linked List:\n");
        n = walkList();
        printf("\nNo of elements in linked list: %d\n", n);
        printf("\nData in Reversed Linked List:\n");
        reverseList();
        n = walkList();
        printf("\nNo of elements in linked list: %d\n\n", n);
        deleteList();
        return 0;
  }
Output: (C Program To Reverse Singly Linked List)
  6 5
  7 4
  8 2
 
  Data in Linked List:

  6 5 7 4 8 2 

  No of elements in linked list: 6

  Data in Reversed Linked List:


  2 8 4 7 5 6 

  No of elements in linked list: 6

No comments:

Post a Comment