题目:http://www.patest.cn/contests/pat-a-practise/1074
转自:http://blog.csdn.net/xtzmm1215/article/details/43195793
法一:http://www.cnblogs.com/claremore/p/4802164.html
Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if K = 4, you must output 4→3→2→1→5→6.
Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (<= 105) which is the total number of nodes, and a positive K (<=N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Data Next
where Address is the position of the node, Data is an integer, and Next is the position of the next node.
Output Specification:
For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 6 4 //第一行:链表的首地址add,结点个数n,每隔k个进行一次反转 00000 4 99999 //后面n行:结点的地址address,数据data,下一个结点的地址next 00100 1 12309 68237 6 -1 33218 3 00000 99999 5 68237 12309 2 33218
Sample Output:
00000 4 33218 //反转之后的结果 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
题目大意:
反转单链表,给定常数K和单链表L,要求按每K个节点反转单链表,如:L: 1->2->3->4->5->6 K=3,输出:3->2->1->6->5->4,如果K=4,输出:4->3->2->1->5->6.
特殊情况:
1. 有其他链表干扰(即有多个-1出现):找链表有效长度
2. k=1 或者 k=n :不变 或者 全部逆序
3. 需逆序的起点大于有效长度 : 直接输出原链表
推荐测试:
1. k=1或者k=n:
00100 6 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3
00000
99999 5 68237
12309 2 33218
2. 有其他链表干扰(即有多个-1出现):
00100 6 2
00000 4 99999
00100 1 12309
68237 6 -1
33218 3
-1
99999 5 68237
12309 2 33218
代码:
#include <stdio.h> #include <vector> #include <algorithm> using namespace std; #define MAXN 100001 typedef struct{ int addr; int data; int next; }Node; Node nodes[MAXN]; vector<Node> list; int main() { int firstAdd, n, k; scanf("%d%d%d", &firstAdd, &n, &k); while(n--){ Node nn; scanf("%d%d%d", &nn.addr, &nn.data, &nn.next); nodes[nn.addr] = nn; //方便存入结构体数组 } int address = firstAdd; while(address != -1){ //按地址依次存入list中 list.push_back(nodes[address]); address = nodes[address].next; } int length = list.size(); //有效长度(address == -1 结束) int round = length/k; //需逆序几组 for(int i = 1; i <= round; ++i){ int start = (i-1)*k; int end = i*k; reverse(list.begin() + start, list.begin() + end); //#include <algorithm> } for(int i = 0; i < length-1; ++i){ printf("%05d %d %05d ", list[i].addr, list[i].data, list[i+1].addr); } //最后一个节点的next为-1 printf("%05d %d %d ",list[length-1].addr, list[length-1].data, -1); return 0; }