PAT A1052 Linked List Sorting連結串列排序 (用靜態連結串列 排序)
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.
連結串列包含一系列結構體,這些結構體在記憶體中並不需要連續儲存,我們假設每一個結構體包含一個整數key和一個指向下一個結構體的指標Next。現在給你一個連結串列,你需要按照他們key值大小進行遞增排序。
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive N (<10^5) 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 [−10^5,10^5], 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.
每一個輸入檔案都包含著一個測試用例。每一個測試用例中,第一行包含一個正數N(<10^5)和頭結點的地址,N是記憶體中的節點總數,每個節點的地址都是一個5位正整數,NULL用-1表示。隨後有N行,每一行都描述了一個節點資訊,格式如下
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.
對於每個測試用例,輸出格式與輸入格式相同,其中n是列表中節點的總數,所有節點都必須按順序排序。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
int address;
int key;
int next;
bool flag;
}node[maxn];
bool cmp(Node a,Node b){
if(a.flag==false||b.flag==false){//無效節點排到後面
return a.flag>b.flag;
}else{
return a.key<b.key;//若都是有效節點,按key值從小到大排列
}
}
int main(){
for(int i=0;i<maxn;i++){
node[i].flag=false;
}
//-----------接收輸入----------------------
int n,start;
scanf("%d %d",&n,&start);
int address,key,next;
for(int i=0;i<n;i++){
scanf("%d %d %d",&address,&key,&next);
node[address].key=key;
node[address].next=next;
node[address].address=address;
//node[address].flag=true;
}
//---------遍歷連結串列,標記有效節點----------
int count=0,p=start;
while(p!=-1){
node[p].flag=true; //標記有效節點
count++; //記錄有效節點數目
p=node[p].next;
}
//----------輸出---------------
if(count==0){ //若連結串列為空
printf("0 -1");
}else{
//在sort函式裡篩選有效結點,並按data從小到大排列
sort(node,node+maxn,cmp);
//輸出結果
printf("%d %05d\n",count,node[0].address);
for(int i=0;i<count;i++){
if(i!=count-1){
printf("%05d %d %05d\n",node[i].address,node[i].key,node[i+1].address);
}else{
printf("%05d %d -1\n",node[i].address,node[i].key);
}
}
}
return 0;
}
關於sort的一般用法https://blog.csdn.net/xiangle1993/article/details/24191075
一開始我在接收輸入時就把所有輸入的節點flag都設為true了,並不是輸入的所有節點資訊都是連結串列中的節點。
1.接收輸入資訊,把節點資訊儲存好
2.根據起始地址遍歷連結串列,記錄有效節點個數,並標記有效節點
3.排序,用到sort函式,需自己實現排序方法cmp,無效節點放在後面,有效節點放在前面且有效節點之間按data大小排序。
4.列印結果,注意最後一個節點next為-1時,不能使用%05d輸出