1075 链表元素分类 (25 分)
给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [0, K] 区间内的元素都排在大于 K 的元素前面。但每一类内部元素的顺序是不能改变的。例如:给定链表为 18→7→-4→0→5→-6→10→11→-2,K 为 10,则输出应该为 -4→-6→-2→7→0→5→10→18→11。
输入格式:
每个输入包含一个测试用例。每个测试用例第 1 行给出:第 1 个结点的地址;结点总个数,即正整数N (≤105);以及正整数K (≤103)。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
接下来有 N 行,每行格式为:
Address Data Next
其中 Address
是结点地址;Data
是该结点保存的数据,为 [−105,105] 区间内的整数;Next
是下一结点的地址。题目保证给出的链表不为空。
输出格式:
对每个测试用例,按链表从头到尾的顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。
输入样例:
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
输出样例:
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
采坑点:注意里面的结点可能有多余的无效结点,记得排除
思路:
1.建立一个map<地址,结点信息>储存所有的结点信息,便于直接搜索头节点和根据头结点依次找到接下来的结点
2.建立一个vector<结点>的链表,通过map的信息表建立,
3.遍历vector,将负数节点保存在一个新的数组链表里,将大于k的放在另一个数组链表里,注意结点放入新的链表时原链表的数据元素要进行移动
4.将三个表最终和为一个大表,然后注意修改每个结点的next值为后一个元素的地址即可,最后一个结点next为-1
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<algorithm>
#include<cctype>
#include<map>
using namespace std;
struct node{
string address;
int data;
string next;
};
int main()
{
int n, K,data;
string address, next, first;;
map<string, node>nodes;
cin >> first >> n >> K;
vector<node>list;//输入的结点根据地址排成一个有序的链表
vector<node>templist;//将大于k的值保存在另一个链表
vector<node>templistfushu;//将负数存在另一个链表
vector<node>orederlist;//所有表元素合成一个大表
for (int i = 0; i < n; i++){
cin >> address >> data >> next;
nodes[address].data = data;
nodes[address].next = next;
nodes[address].address = address;
}
cout << endl;
list.push_back(nodes[first]);
int k = 0;
while (list[k].next != "-1"){ //构建一个链表
list.push_back(nodes[list[k].next]);
k++;
}
int fushu = 0;//记录负数个数
for (int i = 0; i < list.size(); i++){
if (list[i].data < 0){
fushu++;
templistfushu.push_back(list[i]);//将负数结点存入新的表里
}
else{
list[i - fushu] = list[i];//负数结点存入后原表的数据元素需要进行移动
}
}
int temp = 0;
for (int i = 0; i < list.size()-fushu; i++){
if (list[i].data>K){
temp++;
templist.push_back(list[i]);
}
else{
list[i - temp] = list[i];
}
}
k = 0;
while (k < templistfushu.size()){
orederlist.push_back(templistfushu[k++]);
}
k = 0;
while (k < list.size() - templistfushu.size() - temp){
orederlist.push_back(list[k++]);
}
k = 0;
while (k < templist.size()){
orederlist.push_back(templist[k++]);
}
for (int i = 0; i < orederlist.size(); i++){
if (i == orederlist.size() - 1){
printf("%s %d %d\n", orederlist[i].address.c_str(), orederlist[i].data,-1);
}
else{
printf("%s %d %s\n", orederlist[i].address.c_str(), orederlist[i].data, orederlist[i + 1].address.c_str());
}
}
return 0;