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.
00100 6 4 00000 4 99999 00100 1 12309 68237 6 -1 33218 3 00000 99999 5 68237 12309 2 33218
00000 4 33218 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
题目大意:一共有n个元素,每k个元素作为一组逆置组,每一个逆置组单独逆置,不足k个元素的组不改变顺序。要注意的是输入有可能会有多余的节点要去除 因为每组单独逆置的第一个一定是这组逆置的最后一个,所以标记第一个,然后后面的插在这个节点的前面 设置两个指针ltailp和tailp。ltailp标记的是上一组逆置的第一个,tailp是当前逆置组的第一个 如果这两个指针相同说明只有一组逆置,不同就说明有多组逆置 用ltailp连接本组逆置的最后一个,解决不同逆置组之间相连问题
还可以用数组模拟链表的实现过程
#include <stdio.h> #include <stdlib.h> #define N 100001 #define HEAD 100000 #define OK 1 #define ERROR 0 typedef int Status; typedef struct Node { int data; int next; }Node; Node L[N]; int Last=HEAD; Status createList(int head,int n); Status reverseList(int k); Status printList(); Status CountNode(int &n); int main() { int head,n,k,m=1; scanf("%d%d%d",&head,&n,&k); createList(head,n); CountNode(n); for(int i=1;i<=n-k+1;i+=k) reverseList(k); printList(); return 0; } Status InitList() { for(int i=0;i<N;i++){ L[i].data=0; L[i].next=-1; } return OK; } Status createList(int head,int n) { InitList(); L[HEAD].next = head; int ads,da,nxt; for(int i=0;i<n;i++){ scanf("%d%d%d",&ads,&da,&nxt); L[ads].data=da; L[ads].next=nxt; } } Status CountNode(int &n) { int p = HEAD; n=0; while(L[p].next != -1){ p=L[p].next; n++; } return OK; } Status reverseList(int k) { int p = Last; int q = Last; Last = L[p].next; for(int i=1;i<=k;i++) q = L[q].next; for(int i=1;i<=k-1;i++){ int temp=L[p].next; L[p].next = L[temp].next; L[temp].next = L[q].next; L[q].next = temp; } return OK; } Status printList() { int p = L[HEAD].next; while(L[p].next!=-1){ printf("d %d d\n",p,L[p].data,L[p].next); p = L[p].next; } printf("d %d %d\n",p,L[p].data,L[p].next); return OK; }