数据结构专题——链表处理A1052.Linked List Sorting(25) (静态链表)
自己写的,少了异常处理。
#include <bits/stdc++.h> #include<math.h> #include <string> using namespace std; const int maxn = 100010; struct Node{//定义静态链表 int data; int address; int next; bool flag; }node[maxn]; bool cmp(Node a,Node b){ //return a.data < b.data; if(a.flag != b.flag){ return a.flag > b.flag; }else{ return a.data < b.data; } } int main(){ int n,addre; scanf("%d%d",&n,&addre); int add,d,nex; for(int i=0;i<n;++i){ scanf("%d%d%d",&add,&d,&nex); node[add].data = d; node[add].next = nex; node[add].flag = true; node[add].address = add; } sort(node,node+maxn,cmp); printf("%d %05d\n",n,node[0].address); for(int i =0;i<n;++i){ if(i != n-1){ node[i].next = node[i+1].address; }else{ node[i].next = -1; } if(i != n-1){ printf("%05d %d %05d\n",node[i].address,node[i].data,node[i].next); }else{ printf("%05d %d %d\n",node[i].address,node[i].data,node[i].next); } } system("pause"); return 0; }
由于题目可能会有无效节点,即不在题目给出的首地址开始的链表上
数据里面还有全部是无效的情况,这时就要根据有效节点的个数特判输出“0 -1”
#include <bits/stdc++.h> #include<math.h> #include <string> using namespace std; const int maxn = 100010; struct Node{//定义静态链表 int data; int address; int next; bool flag; }node[maxn]; bool cmp(Node a,Node b){ //return a.data < b.data; if(a.flag != b.flag){ return a.flag > b.flag; }else{ return a.data < b.data; } } int main(){ for(int i=0;i<maxn;++i){ node[i].flag = false; } int n,begin,address; scanf("%d%d",&n,&begin); for(int i =0;i<n;++i){ scanf("%d",&address); scanf("%d%d",&node[address].data,&node[address].next); node[address].address = address; } int count = 0,p = begin; //枚举链表,对flag进行标记,同时计数有效节点个数 while(p != -1){ node[p].flag = true; count++; p = node[p].next; } if(count == 0){//特判,新链表中没有节点时输出0 -1 printf("0 -1"); }else{ //筛选有效节点,并按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].data,node[i+1].address); }else{ printf("%05d %d -1\n",node[i].address,node[i].data); } } } system("pause"); return 0; }
相关推荐
Cypress 2020-01-18