题目来源:PAT (Advanced Level) Practice
A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.
Each input file contains one test case. For each case, the first line contains a positive N (<105) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by ?1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the address of the node in memory, Key is an integer in [?105,105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.
Output Specification:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
words:
adjacent 临近的????????memory 记忆,存储????????assume 假设
题意:
给出n个结点和链表的起始结点,要求输出按照关键字key升序排序后的链表;注:有些结点可能不在链表中,所有不参与排序;
思路:
1. 设置一个结构体用于存储结点的信息;
2. 将所有的结点存放在数组中v[]中,其中v[]的下标对应存放的结点的地址;并且将所有的结点标记为false(表示不在链表中);
3. 通过链表的起始地址遍历整个链表,将遍历到的结点标记为true(表示在链表中);
4. 对所有的结点进行排序,将标记为true的结点排在前面,将标记为false的结点排在后面;
5. 对所有标记为true的结点按照关键字key的大小进行升序排序;
6. 输出排完序后的且标记为true的结点即可;
//PAT ad 1052 Linked List Sorting
#include <iostream>
using namespace std;
#include <algorithm>
#include <iomanip>
#include <vector>
#define N 100005
struct link //结点
{
int address;
int key;
int next;
};
bool cmp1(pair<link,bool> x,pair<link,bool> y)
{
return x.second>y.second;
}
bool cmp(pair<link,bool> x,pair<link,bool> y)
{
return x.first.key<y.first.key;
}
int main()
{
int start,n,k,i,x;
cin>>n>>start;
vector<pair<link,bool> > v(N); //存放所有结点
int address,key,next;
for(i=0;i<n;i++) //输入
{
cin>>address>>key>>next;
v[address].first.address=address;
v[address].first.key=key;
v[address].first.next=next;
v[address].second=false;
}
int c=0;
for(i=0;start!=-1;i++) //标记链表中的结点
{
v[start].second=true;
start=v[start].first.next;
}
n=i; //链表中结点的个数
sort(v.begin(),v.end(),cmp1); //排序,把在链表中的结点排到前面去
sort(v.begin(),v.begin()+n,cmp); //排序,把前面的结点(链表中的结点)按照key的大小进行升序排序
cout<<n<<" "; //输出链表中结点的个数
for(i=0;i<n;i++) //输出
{
cout<<setw(5)<<setfill('0')<<v[i].first.address<<endl;
cout<<setw(5)<<setfill('0')<<v[i].first.address<<" "<<v[i].first.key<<" ";
}
cout<<"-1"<<endl;
return 0;
}
|