PTA 重排链表 题解

L2-2 重排链表

注意事项:

有的测试数据中会包含错误结点,这些结点不会被用上。所以这道题还是挺坑的。

思路:

这道题我选择用数组去模拟链表。

  • 首先用结构体写一个结点,用来模拟双链表。next与front表示最初的关系。结点中的newnext项表示排序后的关系。
  • 进行读取数据,并将头结点和尾结点进行记录。
  • 首尾结点指针轮流向中间移动,同时建立新的链接。
  • 我用了flag变量控制首尾结点的轮流移动以及奇偶数控制。(但可读性很差)
  • 最后输出新链表。注意%05d的输出格式。
#include <iostream>
#include <cstdio>
using namespace std;

struct Node
{
    int data;
    int next;
    int front;
    int newnext;
};
struct Node node[100050];

int main()
{
    int head, n, end, newhead;
    cin >> head >> n;
    for (int i = 0; i < n; i++)
    {
        int address;
        cin >> address;
        cin >> node[address].data >> node[address].next;    
        if(node[address].next == -1){
            end = address;
            newhead = address;
        }
        else{
            node[node[address].next].front = address;
        }
    }

    int flag = false;
    node[end].newnext = head;
    while(node[head].next != end)
    {   
        if(flag){
            head = node[head].next;
            node[end].newnext = head;            
            flag = !flag;
        }
        else{
            end = node[end].front;
            node[head].newnext = end;
            flag = !flag;
        }
               
    }
    if(flag)
        node[end].newnext = -1;
    else
        node[head].newnext = -1;

    while(newhead != -1)
    {
        if(node[newhead].newnext !=-1)
            printf("%05d %d %05d\n", newhead, node[newhead].data, node[newhead].newnext);
        else
            printf("%05d %d -1\n", newhead, node[newhead].data);
        newhead = node[newhead].newnext;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FengLing255

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值