Search This Blog

Tuesday, 27 September 2016

Reversing Link List in group of n nodes without using any other data type in O(n) time

Some ways of reversing a link list using other data types are-
1.Use the stack. We can push all the elements on to the stack and then poop out each element. 
2.Similarly, we can also create a new link list. Starting from the head of the current list, we can create  new list by adding nodes in the front of the new list.

A link list can be reversed without using any other data type by using three pointers as shown in the code below.



//created by Aditya Vijayvergia
//uploaded on thecodingedge.blogspot.com
#include<stdio.h>
#include<conio.h>
struct node
{
  int data;
  struct node* next;
}*head;
typedef struct node node;
 
node* rev(int n)
{
  node *p,*q,*r,*t2,*t1;
  int c=0,start=1;
  t2=head;
  t1=NULL;
  p=head;
  q=head->next;
  r=q->next;
  while(q!=NULL)
  {
    //printf("c<n-1\n\t%d",p->data);
    //getch();
    if(c==n-1)
    {
      //printf("c=n-1");
      //getch();
      c=0;
      if(t1!=NULL)
    t1->next=p;
      t1=t2;
      t2=q;
      if(start==1)
      {
    start=0;
    head=p;
      }
      p=q;
      q=p->next;
      r=q->next;
    }
    q->next=p;
    p=q;
    q=r;
    r=r->next;
    c++;
  }
  t1->next=p;
  t2->next=NULL;
  return head;
}
 
 
 
void main()
{
  node *q;
  node* p;
  int i;
  clrscr();
  head=(node*)malloc(sizeof(node));
  p=head;
  //q->next=NULL;
  head->data=1;
  //p->next=NULL;
  for(i=2;i<15;i++)
  {
    q=(node*)malloc(sizeof(node));
    q->next=NULL;
    q->data=i;
    p->next=q;
    p=p->next;
  }
  p=head;
  printf("Initial link list is:\n");
  while(p!=NULL)
  {
    printf("%d->",p->data);
    p=p->next;
  }
  printf("\n\n\n\nUsing n=3\n");
  head=rev(6);
  p=head;
  printf("\n\n\nReversed link list is:\n");
  while(p!=NULL)
  {
    printf("%d->",p->data);
    p=p->next;
  }
  getch();
}



The output of the program is given below.

No comments:

Post a Comment