【PTA】重排链表

题目重述

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

输入格式:

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

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

Address Data Next

其中Address是结点地址;Data是该结点保存的数据,为不超过10​5​​ 的正整数;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的时候,说明输出完了,即可退出。

C++ AC

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node{
    int data;
    int next;
};
node nds[100010];
int pre[100010];
int main()
{
    int first,n;
    cin>>first>>n;
    int address;
    for(int i=1;i<=n;i++)
    {
        cin>>address;
        cin>>nds[address].data>>nds[address].next;

    }
    int loc=first;//初始loc等于首结点
    n=1;
    while(nds[loc].next!=-1)
    {
        n++;//记录链表中实际的节点数量
        pre[nds[loc].next]=loc;
        loc=nds[loc].next;
    }
    //cnt用于记录已经输出了几个结点了
    int cnt=0;
    while(true)
    {
       printf("%05d %d",loc,nds[loc].data);
       cnt++;
       //如果是最后一个,那么输出的next应该是-1
       if(cnt==n)
       {
           printf(" %d\n",-1);
           break;
       }
       else
       {
          printf(" %05d\n",first);
       }

       printf("%05d %d",first,nds[first].data);
       cnt++;
       loc=pre[loc];//尾结点从后往前
        if(cnt==n)
       {
           printf(" %d\n",-1);
           break;
       }
       else
       {
          printf(" %05d\n",loc);
       }
       first=nds[first].next;//首结点从前往后

    }
    return 0;
}

发布了243 篇原创文章 · 获赞 106 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43889841/article/details/104226283