博客
关于我
[编程题]Linked List Sorting
阅读量:368 次
发布时间:2019-03-04

本文共 1705 字,大约阅读时间需要 5 分钟。

链表查找问题处理方案

问题背景

由于题目给定的输入范围较小,我们可以采用静态链表的方式来解决问题。为了确保链表处理的准确性,我们需要在节点结构体中增加一个标记位,用于记录当前节点是否为有效节点。

输入处理

读取输入后,我们需要注意其中可能包含不在链表中的节点。为了标记这些有效节点,我们需要对链表进行一次遍历,检查每个节点的有效性,并将其标记为有效节点。

节点排序规则

在对节点进行排序时,我们需要遵循以下规则:

  • 有效节点优先于无效节点排序。
  • 有效节点之间按照节点的数据值从小到大排序。
  • 节点标记逻辑

    通过对链表进行一次遍历,我们可以标记所有有效节点。具体实现步骤如下:

  • 初始化一个计数器cnt,用于记录有效节点的数量。
  • 从给定起始节点开始,遍历链表的每个节点。
  • 将遍历到的每个节点标记为有效节点,并增加计数器cnt
  • 排序逻辑

    使用自定义的比较函数对节点列表进行排序。比较函数的逻辑如下:

  • 如果两个节点的有效性不同,优先级高的节点排在前面。
  • 如果两个节点均为有效节点,则按数据值从小到大排序。
  • 代码实现

    #include 
    #include
    #include
    #include
    using namespace std;struct NODE { int ad = -1; int next = -1; int num; int flag = -1; // 标记是否为有效节点};bool cmp(const NODE& n1, const NODE& n2) { if (n1.flag != n2.flag) { return n1.flag > n2.flag; } else { return n1.num < n2.num; }}int main() { int ad, n; cin >> ad >> n; vector
    nodes(maxn); for (int i = 0; i < n; ++i) { int a1, a2; int num; cin >> a1 >> a2 >> num; nodes[a1].ad = a1; nodes[a1].num = num; nodes[a1].next = a2; } int p = ad; int cnt = 0; while (p != -1) { nodes[p].flag = 1; cnt++; p = nodes[p].next; } sort(nodes.begin(), nodes.end(), cmp); if (nodes[0].ad != -1) { printf("%d %05d\n", cnt, nodes[0].ad); } else { printf("%d %d\n", cnt, nodes[0].ad); } for (int i = 0; i < maxn; ++i) { if (i > 0) { cout << endl; } if (nodes[i].flag == 1) { cout << nodes[i].ad << " " << setw(5) << nodes[i].num; } }}

    输出格式说明

    • 有效节点数量以%d格式输出。
    • 有效节点的起始地址和数据值以%05d格式输出,以便于对齐。
    • 无效节点的起始地址和数据值直接以%d格式输出。

    通过以上实现,我们可以高效地解决链表查找问题,并确保输出格式符合要求。

    转载地址:http://ziyg.baihongyu.com/

    你可能感兴趣的文章
    Struts2中使用Session的两种方法
    查看>>
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>