• 1052 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.

    Input Specification:

    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.


    Sample Input:

    1. 5 00001
    2. 11111 100 -1
    3. 00001 0 22222
    4. 33333 100000 11111
    5. 12345 -1 33333
    6. 22222 1000 12345

    Sample Output:

    1. 5 12345
    2. 12345 -1 00001
    3. 00001 0 11111
    4. 11111 100 22222
    5. 22222 1000 33333
    6. 33333 100000 -1

    题目大意

    给你一个链表,每个data都有对应的adress,请你按data从小到大排序后依次输出


    思路

    pair  adress + data,sort直接根据data排序即可


    C/C++ 

    1. #include
    2. using namespace std;
    3. bool cmp(pair<int,int> x, pair<int,int> y){
    4. return x.second < y.second;
    5. }
    6. int main()
    7. {
    8. int N, head, num,data[100001],next[100001];
    9. cin >> N >> head;
    10. while (N--) {
    11. cin >> num;
    12. cin >> data[num] >> next[num];
    13. }
    14. vectorint,int>> result;
    15. while (head!=-1){
    16. result.emplace_back(head,data[head]);
    17. head = next[head];
    18. }
    19. sort(result.begin(),result.end(),cmp);
    20. cout << result.size() << " ";
    21. for(auto x:result) printf("%05d\n%05d %d ",x.first,x.first,x.second);
    22. cout << "-1";
    23. return 0;
    24. }


     

  • 相关阅读:
    使用Web 在IntelliJ IDEA 下创建、部署、运行及更改端口号、添加 Tomcat 依赖
    LeetCode[105]从前序与中序遍历序列构造二叉树
    Go语言中操作Redis
    校园智慧党建小程序源码系统 带完整的搭建教程
    MFC Windows 程序设计[114]之多样下拉列表框
    【Docker仓库】使用华为云SWR容器镜像仓库服务
    modern C++:闭包与匿名函数
    支持向量机
    Redis - 基础数据类型
    xv6源码阅读——中断与异常
  • 原文地址:https://blog.csdn.net/daybreak_alonely/article/details/127875021