原题链接: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
题目大意:
给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [0,K]
区间内的元素都排在大于 K
的元素前面。但每一类内部元素的顺序是不能改变的。
例如:给定链表为 18→7→-4→0→5→-6→10→11→-2
,K 为 10,则输出应该为 -4→-6→-2→7→0→5→10→18→11
。
简而言之:
给一个链表和K,遍历链表后将<0的结点先输出,再将0~k区间的结点输出,最后输出>k的结点。
方法一:静态链表
思路:
用结点的结构体数组来存储链表,下标代表结点的地址,里面存结点的值以及next的地址。根据题目要求,将结点的地址分为三类(<0的、0~k的、大于k的)放入二维数组中,最后输出即可。
C++ 代码:
#include <iostream>
#include <vector>
using namespace std;
struct node {
int data, next;
}list[100000]; // list的下标是结点的地址
vector<int> v[3]; // 一维长度为3,二维长度可变的矩阵
int main() {
int start, n, k, a; // start第一个结点地址、n结点个数、给定的k
scanf("%d %d %d", &start, &n, &k);
while(n--){
scanf("%d", &a); // 地址
scanf("%d%d", &list[a].data, &list[a].next); // 的值、next的地址
}
int p = start;
while(p != -1) {
int data = list[p].data;
if (data < 0)
v[0].push_back(p); // 小于0的部分
else if (data >= 0 && data <= k)
v[1].push_back(p); // 0到k的部分
else
v[2].push_back(p); // k到n的部分
p = list[p].next;
}
int flag = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < v[i].size(); j ++ ) {
if (flag == 0) {
printf("%05d %d ", v[i][j], list[v[i][j]].data); // 第一个先输出地址、值
flag = 1;
} else {
printf("%05d\n%05d %d ", v[i][j], v[i][j], list[v[i][j]].data); // 后面的输出前一次的next和本次的地址和值
}
}
}
printf("-1"); //最后补上-1
return 0;
}
复杂度分析:
- 时间复杂度:O(n),顺序遍历一遍链表,再输出
- 空间复杂度:O(n),二维数组刚好存储每个结点