您的位置:首页 > 其它

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

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐