Thursday, March 15, 2012

Reverse a linked list every "given num" nodes

#include<stdio.h>
#include<stdlib.h>
struct node
  {
    int val;
    struct node* next;
  };
struct node *current=NULL,*temp=NULL,*prev=NULL,*header1=NULL,*header2=NULL,*header3=NULL;
struct node* head=NULL,*A=NULL,*B=NULL,*C=NULL,*last=NULL;
struct node* createlist(struct node* header);
void print(struct node* header);
main()
 {
int number;
   int x,sum;
   char ch;
   int i=1;
   int flag=1;
   header1=malloc(sizeof(struct node));
   header1->next=NULL;
   printf("\n enter the value to be put in the header node" );
   scanf("%d",&x);
   header1->val=x;
   createlist(header1);
   print(header1);
   printf("\n enter after how many nodes reversal");
   scanf("%d",&number);
   A=B=C=head=header1;
   while(B!=NULL)
   {
       for(i=1;i<=number-1;i++)
       {
         if(A==head)
         {
             A=A->next;
             printf("\n a data %d",A->val);
         }

            B=A->next;
            A->next=head;
            C->next=B;
            head=A;
            A=B;
            if(last!=NULL)
               last->next=head;
       }
       last=C;       C=A;
       if (flag) { header1=head; flag=0;}
       head=A;
   }
   print(header1);
 }
struct node* createlist(struct node* header)
{
    int x;char ch;
     current=header;
   temp=header;
   do
    {
      current=malloc(sizeof(struct node));
      printf("\n enter the value to be put in it \n");
      scanf("%d",&x);
      current->val=x;
      temp->next=current;
      temp=current;
      getchar();
      printf("\n want  MORE \n");
      scanf("%c",&ch);
      printf("\n char entered is %c",ch);
    }while(ch=='y');
  current->next=NULL;
  current=header;
}

void print(struct node* header)
{
current=header;
 while(current!=NULL)
  {
   printf("\n value is %d",current->val);
   current=current->next;
  }
}

No comments:

Post a Comment