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
【题解】
新建3条链表,分别存负数,[0,k]的数以及大于k的数。然后将三条链表窜起来
当然,更省事的,就直接使用3个queue分别记录三组数据,然后输出,
两个方法差不多,容器的更方便,但链表的不用额外空间
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 struct Node 5 { 6 int val, next; 7 }List[100010]; 8 int head, n, k; 9 int main() 10 { 11 cin >> head >> n >> k; 12 while (n--) 13 { 14 int address, data, next; 15 cin >> address >> data >> next; 16 List[address].val = data; 17 List[address].next = next; 18 } 19 int head1 = 100001, head2 = 100002, head3 = 100003;//分别是负数、中间数、>k数的链表 20 int p = head, p1 = head1, p2 = head2, p3 = head3; 21 while (p != -1) 22 { 23 if (List[p].val < 0) 24 { 25 List[p1].next = p; 26 p1 = p; 27 } 28 else if (List[p].val > k) 29 { 30 List[p3].next = p; 31 p3 = p; 32 } 33 else 34 { 35 List[p2].next = p; 36 p2 = p; 37 } 38 p = List[p].next; 39 } 40 //这里的顺序千万不要反了,因为next不是地址,要先改变,再赋值 41 List[p3].next = -1; 42 List[p2].next = List[head3].next; 43 List[p1].next = List[head2].next; 44 p = List[head1].next; 45 while (List[p].next != -1) 46 { 47 printf("%05d %d %05d ", p, List[p].val, List[p].next); 48 p = List[p].next; 49 } 50 printf("%05d %d %d ", p, List[p].val, List[p].next); 51 return 0; 52 }