1074 Reversing Linked List (25 分)
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:
1 | 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:
1 | 00100 6 4 |
Sample Output:
1 | 00000 4 33218 |
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
题目大意
给出一个链表,给出k,要求以k为一组翻转链表
分析
使用map<int,node>
记录地址和结点,利用vector<node>
暂存结点。从头结点开始,读取k个结点进vector,将其翻转。判断剩余结点是否大于k个。如果大于k个,则vec[0]结点的next为向后数k个结点的地址。如果小于则不翻转,对应的next为vec[k-1]的next。
代码
1 |
|
其他
注意测试点5的情况,对应 L%k=(k-1)的情况。例如7个结点,k=4。