实现单链表的倒置(两种方法)
2023-03-20 14:49:38 时间
# conding:utf8 class Node(): def __init__(self, _item): self.item = _item self.next = None class Link(): def __init__(self): self._head = None def append(self, _item): node = Node(_item) cur = self._head pre = None if cur == None: self._head = node return while cur: pre = cur cur = cur.next pre.next = node def travel(self): cur = self._head while cur: print(cur.item) cur = cur.next # 方式一:三个变量实现单链表倒置 def reverse1(self): pre = None cur = self._head next_node = cur.next while cur: cur.next = pre pre = cur cur = next_node if next_node: next_node = next_node.next self._head = pre # 方式二:两个变量实现单链表的倒置 def reverse2(self): pre = None cur = self._head while cur: temp = cur.next cur.next = pre pre = cur cur = temp self._head = pre if __name__ == "__main__": link = Link() link.append(1) link.append(2) link.append(3) link.travel() print("---------------------------") link.reverse1() link.travel()
输出结果:
1 2 3 --------------------------- 3 2 1
相关文章
- Windows 11的设备管理器开始默认不读取A:\软驱
- Windows 11优化设备管理器:更新驱动的默认路径终于不再是软驱A盘了
- 在 Linux 中像专业人士一样使用 GNOME 截图工具
- Fedora 36 将移除对 ifcfg 的支持
- 在浏览器中,把 Vite 跑起来了!
- Iot前端Node-Red+ IOT Studio + Github无法访问解决办法
- 惊喜:Windows 11 仍然支持运行 5.25 寸软盘
- Centos8中恢复根目录为默认权限
- Firefox 95 和 Chrome 97 在 Linux 的性能对比
- Maui Shell 来了,开启 Linux 桌面新时代!
- Linux下几种运行后台任务的方法
- Canonical正重构Snap应用安装包:更细、更模块化
- Windows11越来越“苹果化”是好还是坏?
- Linux中对【库函数】的调用进行跟踪的三种【插桩】技巧
- Windows 11仍不够苹果?一招魔改Windows 11任务栏
- Windows 11 22526新版修复大量问题!新特性抢先看
- Windows 11 Alt+Tab切换界面升级:越来越像苹果了
- AirPods音质更好Windows 11更新修复大量问题
- 苹果Mac电脑,能否避开Tpm限制?苹果电脑安装Windows 11操作系统方法
- Windows 10操作系统,怎么一键系统还原?Windows 10一键还原操作步骤