PAT_A1133#Splitting A Linked List

Source:

PAT A1133 Splitting A Linked List (25 分)

Description:

Given a singly linked list, you are supposed to rearrange its elements so that all the negative values appear before all of the non-negatives, and all the values in [0, K] appear before all those greater than K. The order of the elements inside each class must not be changed. For example, given the list being 18→7→-4→0→5→-6→10→11→-2 and K being 10, you must output -4→-6→-2→7→0→5→10→18→11.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤) which is the total number of nodes, and a positive K (≤). The address of a node is a 5-digit nonnegative integer, and NULL is represented by −.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer in [, and Next is the position of the next node. It is guaranteed that the list is not empty.

Output Specification:

For each case, output in order (from beginning to the end of the list) the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

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

Sample Output:

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

Keys:

  • 链表
  • 散列(Hash)

Code:

 1 /*
 2 Data: 2019-08-09 14:34:04
 3 Problem: PAT_A1133#Splitting A Linked List
 4 AC: 23:34
 5 
 6 题目大意:
 7 重排单链表,不改变原先顺序的前提下,使得
 8 1.负数在前,正数在后;
 9 2.正数中,小于K元素在前,大于K的在后;
10 输入:
11 第一行给出,首元素地址,结点数N<=1e5,阈值K
12 接下来N行,地址,数值,下一个地址
13 输出:
14 地址,数值,下一个地址
15 
16 基本思路:
17 结构体存储链表信息
18 按顺序存储链表中有效的数值,再按要求排序,输出;
19 */
20 #include<cstdio>
21 #include<vector>
22 using namespace std;
23 const int M=1e5+10;
24 struct node
25 {
26     int adr,data,nxt;
27 }link[M],t;
28 vector<node> p1,p2,p;
29 
30 int main()
31 {
32 #ifdef ONLINE_JUDGE
33 #else
34     freopen("Test.txt", "r", stdin);
35 #endif // ONLINE_JUDGE
36 
37     int fst,n,k;
38     scanf("%d%d%d", &fst,&n,&k);
39     for(int i=0; i<n; i++)
40     {
41         scanf("%d%d%d", &t.adr,&t.data,&t.nxt);
42         link[t.adr] = t;
43     }
44     while(fst != -1)
45     {
46         if(link[fst].data < 0)
47             p.push_back(link[fst]);
48         else if(link[fst].data <=k)
49             p1.push_back(link[fst]);
50         else
51             p2.push_back(link[fst]);
52         fst = link[fst].nxt;
53     }
54     p.insert(p.end(),p1.begin(),p1.end());
55     p.insert(p.end(),p2.begin(),p2.end());
56 
57     for(int i=0; i<p.size(); i++)
58     {
59         if(i!=0)    printf("%05d\n", p[i].adr);
60         printf("%05d %d ", p[i].adr, p[i].data);
61     }
62     printf("-1");
63 
64     return 0;
65 }

 

posted @ 2019-06-24 17:35  林東雨  阅读(219)  评论(0编辑  收藏  举报