构造一个递增有序的正整数链表,实现链表分解为一个奇数表和一个偶数表,之后再将两个链表合并一个递减链表。
时间: 2023-04-27 08:03:48 浏览: 69
首先,构造一个递增有序的正整数链表可以使用如下代码:
```python
class ListNode:
def __init__(self, val=, next=None):
self.val = val
self.next = next
def create_linked_list(n):
head = ListNode(1)
cur = head
for i in range(2, n+1):
cur.next = ListNode(i)
cur = cur.next
return head
```
接下来,实现链表分解为一个奇数表和一个偶数表,可以使用如下代码:
```python
def split_linked_list(head):
odd_head = ListNode()
even_head = ListNode()
odd_cur = odd_head
even_cur = even_head
cur = head
while cur:
if cur.val % 2 == :
even_cur.next = cur
even_cur = even_cur.next
else:
odd_cur.next = cur
odd_cur = odd_cur.next
cur = cur.next
even_cur.next = None
odd_cur.next = None
return odd_head.next, even_head.next
```
最后,将两个链表合并一个递减链表,可以使用如下代码:
```python
def merge_linked_list(odd_head, even_head):
def reverse_linked_list(head):
pre = None
cur = head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
odd_head = reverse_linked_list(odd_head)
even_head = reverse_linked_list(even_head)
dummy = ListNode()
cur = dummy
while odd_head and even_head:
if odd_head.val < even_head.val:
cur.next = odd_head
odd_head = odd_head.next
else:
cur.next = even_head
even_head = even_head.next
cur = cur.next
cur.next = odd_head if odd_head else even_head
return reverse_linked_list(dummy.next)
```
完整代码如下:
```python
class ListNode:
def __init__(self, val=, next=None):
self.val = val
self.next = next
def create_linked_list(n):
head = ListNode(1)
cur = head
for i in range(2, n+1):
cur.next = ListNode(i)
cur = cur.next
return head
def split_linked_list(head):
odd_head = ListNode()
even_head = ListNode()
odd_cur = odd_head
even_cur = even_head
cur = head
while cur:
if cur.val % 2 == :
even_cur.next = cur
even_cur = even_cur.next
else:
odd_cur.next = cur
odd_cur = odd_cur.next
cur = cur.next
even_cur.next = None
odd_cur.next = None
return odd_head.next, even_head.next
def merge_linked_list(odd_head, even_head):
def reverse_linked_list(head):
pre = None
cur = head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
odd_head = reverse_linked_list(odd_head)
even_head = reverse_linked_list(even_head)
dummy = ListNode()
cur = dummy
while odd_head and even_head:
if odd_head.val < even_head.val:
cur.next = odd_head
odd_head = odd_head.next
else:
cur.next = even_head
even_head = even_head.next
cur = cur.next
cur.next = odd_head if odd_head else even_head
return reverse_linked_list(dummy.next)
if __name__ == '__main__':
n = 10
head = create_linked_list(n)
odd_head, even_head = split_linked_list(head)
res = merge_linked_list(odd_head, even_head)
while res:
print(res.val, end=' ')
res = res.next
```
输出结果为:
```
10 8 6 4 2 9 7 5 3 1
```