pat甲级 团体天梯赛 L2-022. 重排链表

L2-022. 重排链表

时间限制
500 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

给定一个单链表 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

思路:模拟,不过要注意数据,可能并不是所有的输入数据都会在一张链表上。
AC代码:
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<iomanip>
#include<map>
#include<stack>
#include<set>
using namespace std;
#define N_MAX 100000+100
#define INF 0x3f3f3f3f
int head,n;
struct Node {
  int add, data,next;
  Node() {}
  Node(int add,int data,int next):add(add),data(data),next(next) {}
};
Node node[N_MAX];
map<int, Node>M;
int main() {
  while (scanf("%d%d",&head,&n)!=EOF) {
    M.clear();
    for (int i = 0; i < n;i++) {
      int add, data, next;
      cin >> add >> data >> next;
            M.insert(make_pair(add,Node(add,data,next)));
    }
    int tmp = head,num=0;
    while (M[tmp].next!=-1) {
      node[num++] = M[tmp];
      tmp = M[tmp].next;
    }
    node[num++] = M[tmp];//num不一定等于n,因为给的数据可能不在一张链表上,坑!!
    if (num & 1) {
      int end = num - 1, start = 0;
      while (end>num/2) {  
        printf("%05d %d %05d
", node[end].add, node[end].data, node[start].add);
        end--;
        printf("%05d %d %05d
", node[start].add, node[start].data, node[end].add);
        start++;
      }
      printf("%05d %d %d
", node[end].add, node[end].data, -1);
    }
    else {
      int end = num - 1, start = 0;
      while (end>=num/2) {
        printf("%05d %d %05d
", node[end].add, node[end].data, node[start].add);
        end--;
        if(start==num/2-1)printf("%05d %d %d
", node[start].add, node[start].data, -1);
        else printf("%05d %d %05d
", node[start].add, node[start].data, node[end].add);
        start++;
      }
    }
  }
  return 0;
}

提交代码

原文地址:https://www.cnblogs.com/ZefengYao/p/8525066.html