题目链接:https://pintia.cn/problem-sets/16/problems/664
建立一个最大100000的结构数组,模拟链表,两个域,数据域和指针域。
依次输入地址、值、下一个结点地址。
如输入N个结点,每K个结点进行逆序,少于K的不做处理。
注意:测试时输入可能有不在链表里的结点,我第一次用N和K来控制循环,这个点怎么也过不了,原来N并不是真实的链表结点数,后来又在逆序子函数里判断剩余结点有没有K个,结果复杂度太大导致超时,最后直接在主函数遍历一遍链表,数出了结点数量,再用N,K控制循环,才通过了。
链表的逆转方法:
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define Max 100000 #define Null -1 typedef struct Node* List; struct Node { int num; int next; }L[Max]; int flag = 1; int pp; List reverse(List h, int k) { int cnt = 1; int new_ = h->next; /*while (new_ != Null) { cnt++; new_ = L[new_].next; } if (cnt < k) { flag = 0; return h; }*/ /*cnt = 1; new_ = h->next;*/ int old = L[new_].next; int temp; while (cnt < k) { temp = L[old].next; L[old].next = new_; new_ = old; old = temp; cnt++; } L[h->next].next = old; int w = h->next; h->next = new_; pp = new_; return &L[w]; } int main() { int N, K; int head; if(scanf("%d %d %d",&head,&N,&K)==3){} pp = head; int i,j,add,v,ne; for (i = 0;i < N;i++) { if (scanf("%d %d %d", &add, &v, &ne) == 3) {} if (add >= 0 && add < Max) { L[add].num = v; L[add].next = ne; } } List new_ = (List)malloc(sizeof(struct Node)); new_->next = head; new_->num = -1; List hh = new_; int count = 0; int shabi = head; while ( shabi!= Null) { count++; shabi = L[shabi].next; } N = count; count = N / K; i = 0; int start; while (i<count) { hh = reverse(hh, K); if (!i) start = pp; i++; } while(1) { printf("%05d %d ", start, L[start].num); if (L[start].next != Null) printf("%05d ", L[start].next); else { printf("-1 "); break; } start = L[start].next; } return 0; }