链表的逆转
描述
利用单链表表示一个整数序列,通过一趟遍历,将单链表中所有结点的链接方向逆转。要求空间复杂度为O(1)。
输入
多组数据,每组数据有两行,第一行为链表的长度n,第二行为链表的n个元素(元素之间用空格分隔)。当n=0时输入结束。
输出
对于每组数据分别输出一行,逆序输出链表中的元素,元素之间用空格分隔。
样例输入1
5
1 2 3 4 5
6
3 1 2 5 4 6
0
样例输出1
5 4 3 2 1
6 4 5 2 1 3
解答:尾插法建立链表。遍历链表,采用前插法生成新的逆序链表。遍历新链表,输出相应信息。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
} Node,*List;
void Create(List &L,int n)
{
Node *p,*rear;
L=(Node *)malloc(sizeof(Node));
L->next=NULL;
rear=L;
while(n--)
{
p=(Node *)malloc(sizeof(Node));
scanf("%d",&p->data);
p->next=rear->next;
rear->next=p;
rear=p;
}
}
void Reverse(List &L)
{
Node *p,*q,*head;
p=L->next;
head=L;
head->next=NULL;
while(p)
{
q=p->next;
p->next=head->next;
head->next=p;
p=q;
}
}
int main()
{
int n;
List L;
Node *p;
while(1)
{
scanf("%d",&n);
if(n==0)
break;
Create(L,n);
Reverse(L);
p=L->next;
int first=1;
while(p)
{
if(first)
{
printf("%d",p->data);
first=0;
}
else
{
printf(" %d",p->data);
}
p=p->next;
}
printf("\n");
}
return 0;
}