L2-2 重排链表(25 分)

给定一个单链表 L1L2Ln1Ln,请编写程序将链表重新排列为 LnL1Ln1L2。例如:给定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


用结构体存储链表,然后遍历一遍链表得到地址数组,最后根据奇偶性输出重排后的链表,输出有点小麻烦

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>

using namespace std;
const int N = 1e5 + 3;

struct node{
    int data;
    int next;
}list[N];

int main()
{
    int head, n;
    scanf("%d%d", &head, &n);
    while(n--)
    {
        int id;
        scanf("%d", &id);
        scanf("%d%d", &list[id].data, &list[id].next);
    }
    int id[N], k = 0;
    while(head != -1)
    {
        id[++k] = head;
        head = list[head].next;
    }
    for(int i = 1; i < k; i++)
    {
        if(i % 2 == 1)
        {
            if(i == 1)
                printf("%05d %d", id[k], list[id[k]].data);
            else
                printf(" %05d\n%05d %d", id[k-i/2], id[k-i/2], list[id[k-i/2]].data);
        }
        else
        {
            printf(" %05d\n%05d %d", id[i/2], id[i/2], list[id[i/2]].data);
        }
    }
    printf(" %05d\n%05d %d -1", id[(k+1)/2], id[(k+1)/2], list[id[(k+1)/2]].data);
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值