编程啦1482—001_03

001_03

时间限制:1000 ms  |  内存限制:65535 KB
描述

逆转链表

给定一个链表A(a0, a1, …, an-2,an-1),实现一个链表的逆转操作,得到A’(an-1, an-2, …,a1, a0)。对于有n个元素的线性表,你的算法的运行时间最好应为O(n)。链表中元素为int, 元素个数<N<1,000, 要求用链表实现,检查代码。

[Any Problem: trueshlqsh@gmail.com   ||dengdong1211@sse.buaa.edu.cn||  oeddyo@gmail.com]

输入

输入有2m+1行。第一行为测试数据的组数m。下面的2m行分别为m组测试数据,每组测试数据的第一行为链表元素个数,下面一行为各个元素,链表中的元素用空格隔开。

输出

输入有m行,对应输入的m组测试数据输出逆转后的链表,元素之间用空格隔开。

样例输入
2
10
1 2 3 4 5 6 7 8 9 10
1
1
样例输出
10 9 8 7 6 5 4 3 2 1
1
题目链接:http://www.bianchengla.com/team/123/practise/problem?id=1482
【code】
 1 #include<stdio.h>
2 #include<stdlib.h>
3 struct node
4 {
5 int data;
6 struct node*next;
7 };
8 struct node*creat(int n)
9 {
10 struct node*head,*tail,*p;
11 int i;
12 head=(struct node*)malloc(sizeof(struct node));
13 head->next=NULL;
14 tail=head;
15 for(i=0;i<n;i++)
16 {
17 p=(struct node*)malloc(sizeof(struct node));
18 scanf("%d",&p->data);
19 p->next=NULL;
20 tail->next=p;
21 tail=p;
22 }
23 return head;
24 }
25 void change(struct node*h)
26 {
27 struct node*p=h->next,*q=h->next;
28 q=q->next;
29 p->next=NULL;
30 p=q;
31 while(p!=NULL)
32 {
33 q=q->next;
34 p->next=h->next;
35 h->next=p;
36 p=q;
37 }
38 }
39 void list(struct node*l)
40 {
41 struct node*k;
42 k=l;
43 while(k->next->next!=NULL)
44 {
45 printf("%d ",k->next->data);
46 k=k->next;
47 }
48 printf("%d\n",k->next->data);
49 }
50 int main()
51 {
52 int n,t;
53 scanf("%d",&t);
54 while(t--)
55 {
56 struct node*a;
57 scanf("%d",&n);
58 a=creat(n);
59 change(a);
60 list(a);
61 }
62 return 0;
63 }
 
 
myblog:www.bearac.com
原文地址:https://www.cnblogs.com/pony1993/p/2374075.html