题目如下:
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 00000 4 99999 00100 1 12309 68237 6 -1 33218 3 00000 99999 5 68237 12309 2 33218Sample Output:
00000 4 33218 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
这是一道著名坑题,如果真的用单向链表来做,实在是太变态了,下面给出一种利用map和vector完成的简单方法。
这道题最大的坑在于有无效结点,也就是说除了从头结点走到-1的所有结点外,还有其他子链表,排除的方法很简单,只要从头到尾走一遍记录下来,其他的全部扔掉。
要解决这个问题,需要考虑以下几个方面:
①如何根据题目输入存储结点?
采用结构体数组,规模为10万,下标即为自己的地址,结构体内存储编号和下一个地址。
②如何进行反转?
只用vector记录有效结点的编号,同时在记录时用map记录编号到地址的对应关系。
只反转vector中的编号。
③如何连接地址输出?
通过反转后的vector,结合map查询地址,实现地址连接。
一定要注意处理K=N和N=1的情况,注意地址的前导0,-1不能有前导0。
代码如下:
#include <iostream> #include <stdio.h> #include <map> #include <vector> using namespace std; struct Node{ int me; int num; int next; }nodes[100000]; int main() { int N; map<int,int> addMap; int add,num,next; int head,K; cin >> head >> N >> K; for(int i = 0; i < N; i++){ scanf("%d%d%d",&add,&num,&next); nodes[add].me = add; nodes[add].num = num; nodes[add].next = next; addMap[num] = add; } vector<int> validList; add = head; while(add != -1){ Node n = nodes[add]; validList.push_back(n.num); add = n.next; } vector<int> reverseList; int len = validList.size(); int cur = len; for(int group = 0; group * K < len; group++){ cur = group * K; if(len - cur < K) break; else{ cur = len; for(int i = K - 1; i >= 0; i--){ reverseList.push_back(validList[group * K + i]); } } } for(int i = cur; i < len; i++){ reverseList.push_back(validList[i]); } len = reverseList.size(); if(len == 1){ int num = reverseList[0]; printf("%05d %d -1 ",addMap[num],num); }else{ for(int i = 0; i < len - 1; i++){ int now = reverseList[i]; int next = reverseList[i+1]; printf("%05d %d %05d ",addMap[now],now,addMap[next]); } int now = reverseList[len - 1]; printf("%05d %d -1 ",addMap[now],now); } return 0; }