奇数结点升序偶数结点降序的单链表排序(Python实现)
2024-08-28 20:24:37
题目
一个链表,奇数结点升序,偶数结点降序,要求变成一个全升序的链表。
例如:1->8->2->7->3->6->4->5,变为1->2->3->4->5->6->7->8
解析
按照以下步骤处理:
- 按照奇偶位拆分为两个链表
- 反转偶数结点构成的链表
- 合并两个递增链表
Python实现
# -*- coding:utf-8 -*-
class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def init_list(l):
"""创建不带头结点的单链表"""
head = Node()
tail = head
for val in l:
tail.next = Node(val)
tail = tail.next
tail.next = None
return head.next
def split_list(head):
"""按照奇偶位拆分为两个链表"""
head1 = head2 = None
cur1 = cur2 = None
count = 1
while head:
if count % 2 == 1:
if cur1:
cur1.next = head
cur1 = cur1.next
else:
cur1 = head1 = head
else:
if cur2:
cur2.next = head
cur2 = cur2.next
else:
cur2 = head2 = head
head = head.next
count += 1
cur1.next = None
cur2.next = None
return head1, head2
def reverse_list(head):
"""反转链表"""
if not head or not head.next:
return head
pre = next = None
while head:
next = head.next
head.next = pre
pre = head
head = next
return pre
def merge_list(head1, head2):
"""合并两个递增链表"""
head = Node() # 设置一个临时结点
tail = head
while head1 and head2:
if head1.val <= head2.val:
tail.next = head1
head1 = head1.next
else:
tail.next = head2
head2 = head2.next
tail = tail.next
# 合并剩余结点
if head1:
tail.next = head1
if head2:
tail.next = head2
return head.next
def visit_list(head):
while head:
print(head.val)
head = head.next
if __name__ == '__main__':
head = init_list([1, 8, 2, 7, 3, 6, 4, 5]) # 创建一个不带头结点的单链表:1->8->2->7->3->6->4->5
head1, head2 = split_list(head) # 1.按照奇偶位拆分为两个链表
head2 = reverse_list(head2) # 2.反转偶数结点构成的链表
head = merge_list(head1, head2) # 3.合并两个递增链表
visit_list(head) # 遍历链表
最新文章
- Linux下的磁盘分割和文件系统
- nodejs 遍历数组的两种方法
- Java中 实现多线程成的三种方式(继承,实现,匿名内部类)
- sox linux 下运用
- H5实现俄罗斯方块(四)
- 【转】MYSQL入门学习之十:视图的基本操作
- Nosql释义
- netsh命令
- 让Java的反射跑快点
- 动态绑定Gridview带模板列
- iOS8开发~Swift(一)入门
- 尚学堂马士兵struts2 课堂笔记(四)
- pyinstaller深入使用,打包指定模块,打包静态文件
- SQL Server 2005无法远程连接的解决方法 (转帖)
- 20155226 2016-2017-2 《Java程序设计》第5周学习总结
- 第108天:Ajax中XMLHttpRequest详解
- python内置函数之print()
- 20145303 实验一 Java开发环境的熟悉(Linux + Eclipse)
- spring-springmvc code-based
- JavaScript中的事件代理/委托
热门文章
- Azkaban2.5安装部署(系统时区设置 + 安装和配置mysql + Azkaban Web Server 安装 + Azkaban Executor Server安装 + Azkaban web server插件安装 + Azkaban Executor Server 插件安装)(博主推荐)(五)
- 最全的Spring注解详解
- vue2.0:(八-2)、外卖App弹窗部分sticky footer
- 浅析HTML的元素类型及其转换
- Kendo UI 单页面应用(二) Router 类
- Kendo MVVM 数据绑定(十一) Value
- javascript组件封装中一段通用代码解读
- java项目定时任务实现
- Android tess_two Android图片文字识别
- jquery解析xml,获取xml标签名