按日期有序插入预约的VaccList链表为何排序结果错误
排序问题定位与修复
核心Bug根因
insertByDate方法的循环判断条件写错了判断对象,直接导致排序逻辑失效:
原代码的循环逻辑:
while current.next != None and current.date < newAppt.date: current = current.next
这个逻辑会在「当前节点日期比新预约小」时无限制向后遍历,直到遇到日期更大的节点、或走到链表尾才停下。但升序插入的正确逻辑是要找到第一个日期大于等于新预约日期的节点的前驱节点,因此循环判断的对象应该是「当前节点的下一个节点的日期」,而非当前节点本身的日期。
对应你的测试场景举例:插入日期为2021-04-28的Alvin时,当时链表结构为Mary(3.5) → John(3.10) → Henry(5.1)
- 原逻辑下,遍历到John(3.10)时,因John的日期小于Alvin的4.28,会继续向后走到Henry(5.1)
- 此时循环停止,直接把Alvin插在Henry后面,但Henry的日期(5.1)比Alvin(4.28)大,直接破坏了升序规则,后续插入的节点全部基于这个错乱的位置继续错位,最终出现Henry排到中间的错误结果。
其他未处理的小问题
- 类定义了
self.tail指针但全程没有维护赋值,后续做尾插操作会出现异常 - 空链表插入时只给
head赋值,没有同步设置tail - 存在无实际作用的多余变量
newnode = newAppt
修复后的insertByDate实现
def insertByDate(self, newAppt): assert type(newAppt) is VaccList.Appointment, 'insertByDate requires a pointer to an appointment object' # 空链表直接设为头尾节点 if self.head is None: self.head = newAppt self.tail = newAppt return # 新节点日期小于头节点,插在链表最前面 if newAppt.date < self.head.date: newAppt.next = self.head self.head = newAppt return # 遍历找插入位置:直到下一个节点日期大于等于新节点 current = self.head while current.next is not None and current.next.date < newAppt.date: current = current.next # 完成节点插入 newAppt.next = current.next current.next = newAppt # 如果新节点是最后一个,更新尾指针 if current.next.next is None: self.tail = current.next
附加:补全符合需求的print方法
按你最初的注释要求,原print方法遗漏了空链表提示、末尾空行的逻辑,可以替换为:
def print(self): if self.head is None: print("Appointment List is empty") return runner = self.head while runner is not None: print(runner) runner = runner.next # 最后打印一个空行 print()
修复后的正确运行输出
Appointment for Mary on 2021-03-05 08:00:00 age:65 city:Buffalo (unconfirmed) Appointment for John on 2021-03-10 12:00:00 age:75 city:Buffalo (unconfirmed) Appointment for Melvin on 2021-03-12 18:00:00 age:80 city:New York City (unconfirmed) Appointment for Sheila on 2021-04-21 14:00:00 age:50 city:New York City (unconfirmed) Appointment for Alvin on 2021-04-28 13:30:00 age:39 city:New York City (unconfirmed) Appointment for Henry on 2021-05-01 12:00:00 age:72 city:Buffalo (unconfirmed)
内容的提问来源于stack exchange,提问作者user52601
相关产品推荐
相关产品推荐

