1074 reverse list

weixin_30488085發表於2020-04-06

最後一個測試用例很坑,注意給出的n個節點不一定都在以h為頭的連結串列上,這種測試用例在PAT連結串列相關的問題中多次出現,要予以注意。

AC程式碼

#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
using namespace std;
class node{
public:
    int addr;
    int v;
    int next;
};
int main(){
    int h,n,k;
    scanf("%d %d %d",&h,&n,&k);
    vector<node> list;
    map<int,node> rec;
    for(int i = 0;i < n;i++){
        node tmp;
        scanf("%d %d %d",&tmp.addr,&tmp.v,&tmp.next);
        rec[tmp.addr] = tmp;
    }
    int addr(h);
    int count(0);
    while(addr != -1){
        list.push_back(rec[addr]);
        addr = rec[addr].next;
    }
    n = list.size();
    if(n < k){
        for(int i = 0;i < list.size();i++){
            if(list[i].next != -1)
                printf("%05d %d %05d\n",list[i].addr,list[i].v,list[i].next);
            else
                printf("%05d %d -1\n",list[i].addr,list[i].v);
        }
        return 0;
    }
    for(int i = 0;i < n / k;i++){
        reverse(list.begin() + i * k,list.begin() + (i+1) * k);
        for(int j = i * k;j < (i+1) * k;j++){
            if(j != (i+1) * k - 1)
                list[j].next = list[j+1].addr; 
        }
    }
    for(int i = 0;i < n / k;i++){
        if((i+1) * k < n)
            list[i * k + k - 1].next = list[(i+1) * k].addr;
        else
            list[i * k + k - 1].next = -1;
    }
    list.back().next = -1;
    for(int i = 0;i < list.size();i++){
        if(list[i].next != -1)
            printf("%05d %d %05d\n",list[i].addr,list[i].v,list[i].next);
        else
            printf("%05d %d -1\n",list[i].addr,list[i].v);
    }
    return 0;
}

 

轉載於:https://www.cnblogs.com/Aldorado/p/5256473.html

相關文章