L2-022. 重排链表

题意:

给定一个单链表 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是下一结点的地址。题目保证给出的链表上至少有两个结点。

输出格式:

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

分析:输入的也许不是个链表,只需要将以给出的第1个结点的地址为开头的链表重排即可。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 100000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int zhi[MAXN];
int nex[MAXN];
int w[MAXN];
int pos[MAXN];
int main(){
    int st, N;
    scanf("%d%d", &st, &N);
    int a, b, c;
    for(int i = 0; i < N; ++i){
        scanf("%d%d%d", &a, &b, &c);
        nex[a] = c;
        zhi[a] = b;
    }
    int tmp = st;
    int cnt = 0;
    while(1){
        ++cnt;
        pos[cnt] = tmp;
        w[cnt] = zhi[tmp];
        if(nex[tmp] == -1) break;
        tmp = nex[tmp];
    }
    int num = 0;
    int id = 0;
    while(1){
        ++num;
        printf("%05d %d ", pos[cnt - id], w[cnt - id]);
        if(num == cnt){
            printf("-1
");
            break;
        }
        else{
            printf("%05d
", pos[1 + id]);
        }
        ++num;
        printf("%05d %d ", pos[1 + id], w[1 + id]);
        if(num == cnt){
            printf("-1
");
            break;
        }
        else{
            printf("%05d
", pos[cnt - id - 1]);
        }
        ++id;
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/8654367.html