The exam was also attended, then directly with the built-in sort, or write their own merger sort of waste time ah, now to practice a pitch. It is estimated that some of the nodes are not in the list, which was not considered at that time, so there have been cases.
#include <iostream>#include<cstdio>#include<vector>#include<unordered_map>using namespacestd;classNode { Public: intdata; intNext; Node (): Data (0), Next (-1) {cout<<"should not happend"<<Endl; } Node (intDintN): Data (d), Next (n) {}};intCountintHead, unordered_map<int, node>&mem) { intCur =Head; intCNT =0; while(cur! =-1) {CNT++; Cur=Mem[cur].next; } returnCNT;}intStepintHeadintK, unordered_map<int, node>&mem) { intCur =Head; while(cur! =-1) { if(k--= =0) { Break; } cur=Mem[cur].next; } returncur;}intMerge_list (intHeada,intHEADB, unordered_map<int, node>&mem) { intNhead =-1; intLast =-1; int Select= -1; intCA = Heada, cb =headb; while(CA! =-1&& CB! =-1) {Node& na =MEM[CA]; Node& nb =MEM[CB]; if(Na.data >nb.data) {Select=CB; CB=Nb.next; } Else if(Na.data <=nb.data) {Select=CA; CA=Na.next; } if(Last = =-1) {Nhead=Select; } Else{Mem[last].next=Select; } Last=Select; } intLast_part =-1; if(CA! =-1) {Last_part=CA; } if(CB! =-1) {Last_part=CB; } if(Last = =-1) {Nhead=Last_part; } Else{Mem[last].next=Last_part; } returnNhead;}intSort_list (intHeadintN, unordered_map<int, node>&mem) { if(N <1) { return-1; } if(n = =1) {Mem[head].next= -1; returnHead; } intA_CNT = n/2; intB_CNT = N-a_cnt; intCA =Head; intCB =Step (head, a_cnt, MEM); CA=Sort_list (CA, a_cnt, mem); CB=sort_list (CB, B_CNT, MEM); returnMerge_list (CA, CB, MEM);}voidPrint_list (intHead, unordered_map<int, node>&mem) { intCur =Head; while(cur! =-1) {Node& cn =Mem[cur]; if(Cn.next = =-1) {printf ("%05d%d%d\n", cur, cn.data, cn.next); } Else{printf ("%05d%d%05d\n", cur, cn.data, cn.next); } cur=Mem[cur].next; }}intMain () {intN, head; scanf ("%d%d", &n, &head); Unordered_map<int, node>Mem; for(intI=0; i<n; i++) { intaddr, data, next; scanf ("%d%d%d", &addr, &data, &next); Mem.insert (Make_pair (addr, Node (data, next)); } intn =count (head, MEM); Head=Sort_list (head, N, Mem); if(N >0) {printf ("%d%05d\n", N, head); } Else{printf ("%d%d\n", N, head); } print_list (head, mem); return 0;}
PAT 1052. Linked List Sorting