【PAT甲級】Linked List Sorting

  • 2019 年 11 月 8 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/weixin_42449444/article/details/89452300

Problem Description:

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.

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.

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.

Sample Input:

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

解題思路:

創建一個結構體數組LinkList,其中包括當前結點的地址address、當前結點的數據data、下一個結點的地址next。按照鏈表結點的地址來將結點排序並依次放入vector中,用cnt來記錄結點vector中的結點數量,當結點數為0時輸出"0 -1"(這個測試點有1分),當結點數不為0時,根據結點數據data來對鏈表進行排序,然後無腦輸出即可。

AC程式碼:

#include <bits/stdc++.h>  using namespace std;  #define MAX 100005    struct LinkList  {      int address;    //當前結點的地址      int data;       //當前結點的數據      int next;       //下一結點的地址  }node[MAX];    bool cmp(LinkList a,LinkList b)   //根據結點數據升序排列  {      return a.data < b.data;  }    int main()  {      int Head,N;   //頭結點Head,結點總個數N      cin >> N >> Head;      for(int i = 0; i < N; i++)      {          int temp;          cin >> temp;          node[temp].address = temp;          cin >> node[temp].data >> node[temp].next;      }      vector<LinkList> v;   //存放鏈表      int cnt = 0;      for(int i = Head; i != -1; i = node[i].next)  //先根據地址來將鏈表排序      {          v.push_back(node[i]);          cnt++;      }      if(cnt == 0)   //當沒有輸入鏈表時      {          printf("0 -1n");      }      else      {          sort(v.begin(),v.end(),cmp);   //根據鏈表的data升序排列          printf("%d %05dn",cnt,v[0].address);          for(int i = 0; i < cnt; i++)          {              printf("%05d %d ",v[i].address,v[i].data);              if(i != cnt-1)              {                  printf("%05dn", v[i+1].address);              }              else              {                  printf("-1n");              }          }      }      return 0;  }