1133 Splitting A Linked List (25 分)
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
map处理一下都好说。
1 #include <bits/stdc++.h> 2 #define N 100005 3 using namespace std; 4 string st; 5 int n,m; 6 struct Node 7 { 8 int val; 9 string s; 10 }an[N],bn[N],cn[N]; 11 map<string,Node> mp; 12 int main(){ 13 ios::sync_with_stdio(false); 14 cin.tie(0); 15 cout.tie(0); 16 cin >> st >> n >> m; 17 string x,y; 18 int z; 19 for(int i = 0 ; i < n; i++){ 20 cin >> x >> z >> y; 21 mp[x]={z,y}; 22 } 23 Node node; 24 int l1 = 0, l2 = 0, l3 = 0; 25 while(st != "-1"){ 26 node = mp[st]; 27 if(node.val < 0){ 28 an[l1++] = {node.val, st}; 29 }else if(node.val >= 0 && node.val <= m){ 30 bn[l2++] = {node.val, st}; 31 }else{ 32 cn[l3++] = {node.val, st}; 33 } 34 st = node.s; 35 } 36 for(int i = 0; i < l2; i++){ 37 an[l1+i] = bn[i]; 38 } 39 l1 = l1 + l2; 40 for(int i = 0; i < l3; i++){ 41 an[l1+i] = cn[i]; 42 } 43 l1 += l3; 44 for(int i = 0; i < l1-1; i++){ 45 cout << an[i].s<<" "<<an[i].val<<" "<<an[i+1].s<<endl; 46 } 47 cout << an[l1-1].s<<" "<<an[l1-1].val<<" "<<"-1"<<endl; 48 return 0; 49 }
原文地址:https://www.cnblogs.com/zllwxm123/p/11306470.html