python选出奇数并降序_奇数结点升序偶数结点降序的单链表排序(Python实现)
題目
一個(gè)鏈表,奇數(shù)結(jié)點(diǎn)升序,偶數(shù)結(jié)點(diǎn)降序,要求變成一個(gè)全升序的鏈表。
例如:1->8->2->7->3->6->4->5,變?yōu)?->2->3->4->5->6->7->8
解析
按照以下步驟處理:
按照奇偶位拆分為兩個(gè)鏈表
反轉(zhuǎn)偶數(shù)結(jié)點(diǎn)構(gòu)成的鏈表
合并兩個(gè)遞增鏈表
Python實(shí)現(xiàn)
# -*- coding:utf-8 -*-
class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def init_list(l):
"""創(chuàng)建不帶頭結(jié)點(diǎn)的單鏈表"""
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):
"""按照奇偶位拆分為兩個(gè)鏈表"""
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):
"""反轉(zhuǎn)鏈表"""
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):
"""合并兩個(gè)遞增鏈表"""
head = Node() # 設(shè)置一個(gè)臨時(shí)結(jié)點(diǎn)
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
# 合并剩余結(jié)點(diǎn)
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]) # 創(chuàng)建一個(gè)不帶頭結(jié)點(diǎn)的單鏈表:1->8->2->7->3->6->4->5
head1, head2 = split_list(head) # 1.按照奇偶位拆分為兩個(gè)鏈表
head2 = reverse_list(head2) # 2.反轉(zhuǎn)偶數(shù)結(jié)點(diǎn)構(gòu)成的鏈表
head = merge_list(head1, head2) # 3.合并兩個(gè)遞增鏈表
visit_list(head) # 遍歷鏈表
總結(jié)
以上是生活随笔為你收集整理的python选出奇数并降序_奇数结点升序偶数结点降序的单链表排序(Python实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: vb 变量赋值为当前选定单元格_第7篇:
- 下一篇: wxpython处理excel_Pyth