L2-022. 重排链表

来源:互联网 发布:切换ip软件 编辑:程序博客网 时间:2024/06/07 13:28

本题要求:

给定一个单链表 L1→L2→…→Ln-1→Ln,请编写程序将链表重新排列为 Ln→L1→Ln-1→L2→…。例如:给定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>using namespace std;class Node {    public:        int data;        int next;        Node() {            data = 0;            next = -1;        }};Node map[100001];int main()  {    int head;    int n;    cin >> head >> n;    for (int i = 0; i < n; i++) {        int a, d, next;        scanf("%d %d %d", &a, &d, &next);        map[a].data = d;        map[a].next = next;    }     int m = 1;    int now = head;    int temp;    int last = -1;    // 计算长度    int length = 0;    while (now != -1) {        length++;        now = map[now].next;    }    now = head;    // 分割后半部分     while (now != -1) {        if (m == length / 2) {            last = map[now].next;            map[now].next = -1;            break;        }        now = map[now].next;        m++;    }    // 倒置第二个链表    int p = last, q = map[last].next, t = -1;    while (q != -1) {        map[p].next = t;        t = p;        p = q;        q = map[p].next;    }    map[p].next = t;    last = p;    // 二个链表交叉合并     now = head;    head = last;    int tempLast, tempNow;    while (now != -1 && last != -1) {        tempLast = map[last].next;        map[last].next = now;        tempNow = map[now].next;        map[now].next = tempLast;        last = tempLast;        now = tempNow;    }    // 输出链表     now = head;    while (now != -1) {        printf("%05d %d ", now, map[now].data);        if (map[now].next != -1) {            printf("%05d\n", map[now].next);        } else {            printf("%d\n", map[now].next);        }        now = map[now].next;    }    return 0;  }  
0 0
原创粉丝点击