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 (≤105) which is the total number of nodes, and a positive K (≤103). The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.
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 [−105,105], 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
题目大意:
给出单链表的起始地址、单链表结点数n与k,要求所有小于k的值都应该在k的前面且保持原来的顺序,比k大的也应该在k的后面且保持他们原本的相对次序。
随后n行即结点的地址 data 和下个结点的地址
思路:
静态链表的题目,肯定都是要先排查一遍,把无关的结点排查出去。
下面确定排序算法,分别用ans[0]、 ans[1], ans[2] 存储 < 0, 0 ~ k, > k三类数,然然后依次打印即可。
参考代码:
#include<vector>
#include<cstdio>
using namespace std;
struct node{
int next, data;
} temp[100000];
vector<vector<int> > ans(3);
int st, n, k;
int main(){
scanf("%d%d%d", &st, &n, &k);
for(int i = 0; i < n; ++i){
int id;
scanf("%d", &id);
scanf("%d%d", &temp[id].data, &temp[id].next);
}
while(st != -1){
if(temp[st].data < 0) ans[0].push_back(st);
else if(temp[st].data > k) ans[2].push_back(st);
else ans[1].push_back(st);
st = temp[st].next;
}
bool flag = false;
for(int i = 0; i < 3; ++i)
for(int j = 0; j < ans[i].size(); ++j)
if(!flag) printf("%05d %d ", ans[i][j], temp[ans[i][j]].data), flag = true;
else printf("%05d\n%05d %d ", ans[i][j], ans[i][j], temp[ans[i][j]].data);
printf("-1");
return 0;
}