Monday, November 1, 2010

Data Structures Part 2

How do you reverse a singly linked list? How do you reverse a doubly linked list? Write a C program to do the same. 

          
             

                     /* SINGLY LINKED LIST */

#include 
#include 

struct linkedList{
 int element;
 struct linkedList *next;
};

typedef struct linkedList* List;

List reverseList(List L)
{
 List tmp, previous=NULL;

 while(L){
  tmp = L->next;
  L->next = previous;
  previous = L;
  L = tmp;
 }
 L = previous;
 return L;
 
}

List recursiveReverse(List L)
{
 List first, rest;
 if(!L)
  return NULL;
 first = L; 
 rest = L->next;
 if(!rest)
  return NULL;
 rest = recursiveReverse(rest);
 first->next->next = first;
 first->next = NULL;
 L=rest;

 return L;
}

No comments:

Post a Comment