• PAT 天梯赛练习集 L2-022. 重排链表


    题目链接:https://www.patest.cn/contests/gplt/L2-022

    给定一个单链表 L1→L2→...→Ln-1→Ln,请编写程序将链表重新排列为 Ln→L1→Ln-1→L2→...。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。

    输入格式:

    每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (<= 105)。结点的地址是5位非负整数,NULL地址用-1表示。

    接下来有N行,每行格式为:

    Address Data Next

    其中Address是结点地址;Data是该结点保存的数据,为不超过105的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。

    输出格式:

    对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。

    输入样例:

    00100 6
    00000 4 99999
    00100 1 12309
    68237 6 -1
    33218 3 00000
    99999 5 68237
    12309 2 33218
    

    输出样例:

    68237 6 00100
    00100 1 99999
    99999 5 12309
    12309 2 00000
    00000 4 33218
    33218 3 -1

    这个的坑点在它没有和你说所有的点一定都是在同一个链表上的,所以最后遍历的时候用存储的长度而不是题目给的n;
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <algorithm>
    #include <string>
    #include <vector>
    #include <queue>
    #include <stack>
    #include <set>
    #include <map>
    #define INF 0x3f3f3f3f
    #define lowbit(x) (x&(-x))
    #define eps 0.00000001
    #define pn printf("
    ")
    using namespace std;
    typedef long long ll;
    
    const int maxn = 1e5+7;
    int z, n;
    struct node{
        int d, k, nx;
    }p[maxn];
    vector <int> vi;
    
    int main()
    {
        scanf("%d%d",&z,&n);
        for(int i=0;i<n;i++)
        {
            int d;
            scanf("%d",&d);
            p[d].d = d;
            scanf("%d%d",&p[d].k,&p[d].nx);
        }
        int s = z;
        while(p[s].nx != -1)
        {
            vi.push_back(s);
            s = p[s].nx;
        }
        vi.push_back(s);
        for(int i=0;i<vi.size();i++)
        {
            if(i&1)
            {
                printf("%05d %d ", p[vi[i/2]].d, p[vi[i/2]].k);
                if(i != vi.size()-1) printf("%05d
    ", p[vi[vi.size()-1-(i+1)/2]].d);
                else printf("-1
    ");
            }
            else
            {
                printf("%05d %d ", p[vi[vi.size()-1-i/2]].d, p[vi[vi.size()-1-i/2]].k);
                if(i != vi.size()-1) printf("%05d
    ", p[vi[(i+1)/2]].d);
                else printf("-1
    ");
            }
        }
    }
  • 相关阅读:
    WCF异常管理—不要在using语句中调用WCF服务(z)
    正则表达式
    nginx汇总(z)
    WCF编解码实现
    zTree -- jQuery 树插件
    C# 程序异常管理方案
    WPF剪切板问题-OpenClipboard HRESULT:0x800401D0 (CLIPBRD_E_CANT_OPEN))
    乘法逆元
    二叉树后序遍历(非递归)
    P1892 [BOI2003]团伙
  • 原文地址:https://www.cnblogs.com/HazelNut/p/8543471.html
Copyright © 2020-2023  润新知