单链表的就地逆序
题目要求将单链表就地逆序个人认为就地逆序应该是将单链表的指针向前移两位,使之指向前一个节点,那么就必须从最后一个指针Null开始,不然就会有数据被覆盖而丢失,但我觉得这样子程序的复杂度会增加很多,所以求高手帮忙提供一种思路能够巧妙地解决这一问题
2011-09-12 23:39

2011-09-13 01:12
程序代码:#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int element;
struct node * next;
}Node,* List;
void CreateList(List &L)
{
Node * p;
L=(List)malloc(sizeof(Node));
L->next=NULL;
for(int i=0;i<5;i++)
{
p=(Node *)malloc(sizeof(Node));
p->element=i;
p->next=L->next;
L->next=p;
}
}
void PrintList(List L)
{
Node *p=L->next;
while(p)
{
printf("%d ",p->element);
p=p->next;
}
printf("\n");
}
void ReverseList(List &L)
{
Node *p,*q;
p=L->next;
q=p->next;
while(p&&q)
{
p->next=q->next;
q->next=L->next;
L->next=q;
q=p->next;
}
}
int main()
{
List A;
CreateList(A);
PrintList(A);
ReverseList(A);
PrintList(A);
return 1;
}简单写了一个逆序函数,顺带测试代码一起写了。不知道符不符合你的意思。
。
2011-09-13 01:51
2011-09-13 08:17
2011-09-13 09:01
2011-09-13 19:51
2011-09-13 20:56
2011-09-14 19:45
2011-09-14 21:35
2011-09-15 13:07