L2-022 重排链表

原题链接

题解

找到终点,然后终点往前移,起点往后移,奇数时输出终点所在位置..直到起点终点重合,这时输出尾节点是-1

code

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data,next,from;
}a[100005];
int main()
{
    int start,n;
    cin>>start>>n;

    int ends;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        cin>>a[x].data>>a[x].next;
        if(a[x].next!=-1)a[a[x].next].from=x;
        else ends=x;
    }

    int cnt=0;
    while(ends!=start)
    {
        cnt++;
        if(cnt&1)
        {
            printf("%05d %d %05d\n",ends,a[ends].data,start);
            ends=a[ends].from;
        }
        else
        {
            printf("%05d %d %05d\n",start,a[start].data,ends);
            start=a[start].next;
        }
    }
    printf("%05d %d -1\n",ends,a[ends].data);
    return 0;
}

posted @ 2024-04-19 13:55  纯粹的  阅读(34)  评论(0)    收藏  举报