Saturday 14 September 2013

reverse k nodes in linked list

#include<stdio.h>
#include<conio.h>

typedef struct node node;

struct node
{
       int info;
       node *next;
};

node *head=NULL;

node *reversekblock(node *root,int k,node **nexttemp,node **temphead)
{
     if(root==NULL)
                   return NULL;
     if(k<=0)
     {
             *nexttemp=root;
             return NULL;
     }
     node *ptr=reversekblock(root,k-1,nexttemp,temphead);
     if(ptr){ ptr->next=root;}
     if(k==1){ *temphead=root;}
     if(root==head){ root->next=(*nexttemp); head=*temphead;}
     return root;        
}

main()
{
      FILE *f=fopen("hinput.txt","r");
      char c[5];
     
      node *ptr,*temp,*given;
      int count,i=0,flag=1;
     
      while(fscanf(f,"%s",c)!=EOF)
      {
                 ptr=(node*)malloc(sizeof(node));
                 ptr->info=atoi(c);
               
                 if(head==NULL)                
                 {
                                head=ptr;
                                ptr->next=NULL;              
                                temp=head;
                                given=head;
                                i+=1;
                 }
                 else
                 {
                                temp->next=ptr;
                                ptr->next=NULL;
                                temp=temp->next;
                               
                                if(i!=count && flag)
                                {
                                            given=given->next;
                                }
                                else
                                    flag=0;
                                    i+=1;
                 }
      }
   
      node *tempn=reversekblock(head,3,NULL,NULL);
      temp=head;
      while(temp!=NULL)
      {
                       printf("\n%d\n",temp->info);
                       temp=temp->next;
      }
      getch();
}

No comments:

Post a Comment

Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.