1075. 链表元素分类

一、题目

给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而[0, K]区间内的元素都排在大于K的元素前面。但每一类内部元素的顺序是不能改变的。例如:给定链表为 18→7→-4→0→5→-6→10→11→-2,K为10,则输出应该为 -4→-6→-2→7→0→5→10→18→11。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出:第1个结点的地址;结点总个数,即正整数N (<= 105);以及正整数K (<=1000)。结点的地址是5位非负整数,NULL地址用-1表示。

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

Address Data Next

其中Address是结点地址;Data是该结点保存的数据,为[-105, 105]区间内的整数;Next是下一结点的地址。题目保证给出的链表不为空。

输出格式:

对每个测试用例,按链表从头到尾的顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。

输入样例:
00100 9 10
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218
输出样例:
33218 -4 68237
68237 -6 48652
48652 -2 12309
12309 7 00000
00000 0 99999
99999 5 23333
23333 10 00100
00100 18 27777
27777 11 -1

二、个人理解

此题考察链表的查找。但实际上若真的采用链表来做,光是生成链表就够喝一壶了。而若是采用数组,一个保存前地址-值,一个保存前地址-后地址,则很容易。


C++:

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    int head, n, k;
    cin >> head >> n >> k;
    int a[100000], b[100000];
    for (int i = 0; i < n; i++) {
        a[i] = -2;
        b[i] = -2;
    }
    //利用数组
    for (int i = 0; i < n; i++) {
        int last, data, next;
        cin >> last >> data >> next;
        a[last] = data;
        b[last] = next;
    }
    int tag = 0, temp = head;
    //三种情况,且不需要考虑坏链情况,因为至少会有一个输出
    while (head != -1 ) {
        if (a[head] < 0) {
            if (tag == 0) {
                printf("%05d %d ", head, a[head]);
                tag = 1;
            } else {
                printf("%05d\n%05d %d ", head, head, a[head]);
            }
        }
        head = b[head];
    }
    head = temp;
    while (head != -1 ) {
        if (a[head] >= 0 && a[head] <= k) {
            if (tag == 0) {
                printf("%05d %d ", head, a[head]);
                tag = 1;
            } else {
                printf("%05d\n%05d %d ", head, head, a[head]);
            }
        }
        head = b[head];
    }
    head = temp;
    while (head != -1 ) {
        if (a[head] > k) {
            if (tag == 0) {
                printf("%05d %d ", head, a[head]);
                tag = 1;
            } else {
                printf("%05d\n%05d %d ", head, head, a[head]);
            }
        }
        head = b[head];
    }
    cout << -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值