链表的就地反转 c语言实现

#include 
typedef struct node
{
  int num;
  struct node *next;
}*LINK,NODE;
LINK link_rev(LINK head);
LINK link_cr(int num);
void link_show(LINK head);

int main()
{
  LINK *p,head,head1;
  head=link_cr(5);
  printf("Now create 5 NODE LINK,print:");

  link_show(head);
  printf("Now REV,print:\n\n");
  head=link_rev(head);
  link_show(head);

  getchar();


}


LINK link_rev(LINK head)
{
  LINK p1,p2,p3;
  p1=p2=p3=head;

  while(p3->next!=NULL)
  {

     if(p3==head)
     {
       p2=p1->next;
       p3=p2->next;
       p1->next=NULL;
       p2->next=p1;
       p1=p2;
       p2=p3;
     }
     else
     {
     p3=p3->next;
     p2->next=p1;
     p1=p2;
     p2=p3;
     }
  }
  p3->next=p1;

  return p3;

}

LINK link_cr(int num)
{
  LINK p1,p2,head;
  int i;
  head=p1=p2=(LINK)malloc(sizeof(NODE));
  p1->num=1;
  for(i=2;i<=num;i++)
  {
    p1=(LINK)malloc(sizeof(NODE));
    p2->next=p1;
    p1->num=i;
    p2=p1;
  }
  p2->next=NULL;
  return head;


}

void link_show(LINK head)
{
  LINK p1=head;
  while(p1!=NULL)
  {
    printf("NODE:%d next Address:%ld \n",p1->num,&(p1->next));
    p1=p1->next;
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *