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

给定一单链表的表头指针 和指向其中一个节点的指针,要求以该指针为头将原链表逆序排列,例如: 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);
 

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值