PAT ---- 反转链表

最近好懒,总想睡觉,效率也不高,反转链表这个题一直困惑着我好长时间,好不容易过了,自己遇到的坑点跟大家分享一下:

1、题目中不保证所有输入的数都为节点

2、注意反转后的链表下一个地址和原来地址不一样

3、最后一个输出-1

 

思想是用结构体来解决,我嫌用指针跳来跳去很麻烦也不好控制,就用了两个对结构体排序的函数来解决

代码:

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int maxn = 1e5+100;
struct Node
{
    int id,data,next,order;
    Node()
    {
        order = maxn;
    }
};
bool cmp(Node a,Node b)
{
    return a.order<b.order;
}
bool cmp_reverse(Node a,Node b)
{
    return a.order>b.order;
}
int main()
{
    Node tmp[maxn];
    int head,n,k,x;
    int cnt = 0;
    cin>>head>>n>>k;
    while(n -- )
    {
        cin>>x;
        cin>>tmp[x].data>>tmp[x].next;
        tmp[x].id = x;
    }
    x = head;
    while(x!=-1)
    {
        tmp[x].order = cnt+1;
        cnt++;
        x = tmp[x].next;
    }
    n = cnt;
    sort(tmp,tmp+maxn,cmp);
    x = 0;
    while(cnt>=k)
    {
        sort(tmp+x*k,tmp+(x*k+k),cmp_reverse);
        x++;
        cnt=cnt-k;
    }
    for(int i=0; i<n-1; i++)
    {
        printf("%05d %d %05d\n",tmp[i].id,tmp[i].data,tmp[i+1].id);
    }
        printf("%05d %d -1\n",tmp[n-1].id,tmp[n-1].data);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

九久呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值