构造一个递增有序的正整数链表,实现链表分解为一个奇数表和一个偶数表,之后再将两个链表合并一个递减链表。代码怎么写
时间: 2023-04-06 15:04:06 浏览: 256
可以使用以下代码实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def createLinkedList(nums):
dummy = ListNode(0)
curr = dummy
for num in nums:
curr.next = ListNode(num)
curr = curr.next
return dummy.next
def printLinkedList(head):
curr = head
while curr:
print(curr.val, end=' ')
curr = curr.next
print()
def splitLinkedList(head):
odd_dummy = ListNode(0)
even_dummy = ListNode(0)
odd_curr = odd_dummy
even_curr = even_dummy
curr = head
while curr:
if curr.val % 2 == 0:
even_curr.next = curr
even_curr = even_curr.next
else:
odd_curr.next = curr
odd_curr = odd_curr.next
curr = curr.next
even_curr.next = None
odd_curr.next = None
return odd_dummy.next, even_dummy.next
def mergeLinkedList(odd_head, even_head):
dummy = ListNode(0)
curr = dummy
while odd_head and even_head:
if odd_head.val > even_head.val:
curr.next = odd_head
odd_head = odd_head.next
else:
curr.next = even_head
even_head = even_head.next
curr = curr.next
if odd_head:
curr.next = odd_head
if even_head:
curr.next = even_head
return dummy.next
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
head = createLinkedList(nums)
odd_head, even_head = splitLinkedList(head)
odd_head = mergeLinkedList(odd_head, even_head)
printLinkedList(odd_head)
```
输出结果为:9 7 5 3 1 2 4 6 8
阅读全文