给定一单链表的表头指针和指向其中一个节点的指针,要求以该指针为头将原链表逆序

来源:互联网 发布:淘宝特种经营有什么用 编辑:程序博客网 时间:2024/06/06 00:16
给定一单链表的表头指针 和指向其中一个节点的指针,要求以该指针为头将原链表逆序排列,例如: N1->N2->N3->N4->N5->NULL pHEAD = N1,pSTART = N3,返回N3->N2->N1->N5->N4->NULL N1->N2->N3->N4->N5->NULL pHEAD = N1,pSTART = N5,返回这个N5->N4->N3->N2->N1->NULL N1->N2->N3->N4->N5->NULL pHEAD = N1,pSTART = N1,返回这个N1->N5->N4->N3->N2->NULL 不允许额外分配存储空间,不允许递归,可以使用临时变量。


#include <stdlib.h>
#include <stdio.h>

struct Node
{
 char data;
 Node *next;
};

void printlist(Node *node)
{
 while (node!=NULL)
 {
  printf("%c ",node->data);
  node=node->next;
 }
 printf("\n");
}
void reverse(Node *head,Node *newhead)
{
 Node *p=head;
 Node *q=head;
 Node *r=head;

 int flag=0;

 if(head==newhead)
 {
  flag=1;
 }

 q=q->next;
 head->next=NULL;

 while (q)
 {
  r=q;
  q=q->next;

  if(flag==0)
  {
   r->next=p;
   p=r;
  }
  else
  {
   if(head->next==NULL)
   {
    head->next=r;
    r->next=NULL;
   }
   else
   {
    r->next=head->next;
    head->next=r;
   }
  }
  if(flag==0 && r==newhead)
   flag=1;
  
 }
 //head->next=NULL;

 printlist(newhead);

}

void main()
{
 Node a,b,c,d,e;
 
 a.data='a';
 a.next=&b;

 b.data='b';
 b.next=&c;

 c.data='c';
 c.next=&d;

 d.data='d';
 d.next=&e;

 e.data='e';
 e.next=NULL;

 printlist(&a);
 reverse(&a,&a);
 

}

原创粉丝点击