Thursday, July 5, 2012

reverse linked list C Code!!

Below is the complete working C code for reverse linked list. Here is the detailed explaination of how to reverse the list.
#include<stdio.h>
#include<stdlib.h>
struct node
{
 int info;
 struct node *next;
};

typedef struct node Node;

/*****************************************************************************
This function is used to create the new linked list or 
adding he new node at the end of the list.
*************************************************************************/

Node* append(Node *h, int info)
{
 Node *tempHead=h;
 Node *newNode = (Node*)malloc(sizeof(Node));
 newNode->info = info;
 newNode->next = NULL;
 if(tempHead == NULL) // if the list has zero elements. make new node as a head
 {
  h=newNode;
 }
 else if(tempHead->next==NULL)  // if the list is having only one node
 {
  tempHead->next = newNode;
 }
 else
 {
  Node *tempNode = h;
  while(tempNode->next != NULL)  // if the list has more than one node, so moving to the last node
  {
   tempNode = tempNode->next;
  }
  tempNode->next = newNode; // appending the new node at the end
 }
 return h;
}


/*****************************************************************************
for displaying the nodes in the list
*****************************************************************************/
void display(Node *h)
{
 Node *temp = h;
 while (temp->next!=NULL)
 {
  printf("%d->",temp->info);
  temp = temp->next;
 }
 printf("%d\n",temp->info);
}

/*****************************************************************************
This function is used to reverse the given linked list. e.g
Input:  1->2->3->4->5->6->7
Output: 7->6->5->4->3->2->1
*****************************************************************************/
Node *reverseList(Node *head)
{
 Node *newHead,*temp;
 temp = head;
 newHead = head;
 if(newHead == temp)
 {
  temp=head->next;
  head = head->next;
  newHead->next = NULL;
 }
 while(head!=NULL)
 {
  temp=head->next;
  head->next = newHead;
  newHead = head;
  head = temp;
 }
 return newHead;
}


main()
{
 Node *head = NULL;
 int i;
 for (i=1;i<=10;i++)
 {
  head = append(head,i*10);
 }
 display(head);
 head =  reverseList(head);
 display(head);

}

Popular Posts