1.将两个递增的有序顺序表合并为一个递增的有序顺序表。 2.将两个递增的有序链表合并为一个递增的有序链表。代码
时间: 2023-10-18 10:27:23 浏览: 131
好的,以下是合并两个递增有序顺序表和链表的代码示例:
1. 合并两个递增有序顺序表
```python
def merge_sorted_lists(lst1, lst2):
i, j = 0, 0
merged_list = []
while i < len(lst1) and j < len(lst2):
if lst1[i] < lst2[j]:
merged_list.append(lst1[i])
i += 1
else:
merged_list.append(lst2[j])
j += 1
merged_list += lst1[i:]
merged_list += lst2[j:]
return merged_list
```
2. 合并两个递增有序链表
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_sorted_lists(head1: ListNode, head2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
while head1 and head2:
if head1.val < head2.val:
curr.next = head1
head1 = head1.next
else:
curr.next = head2
head2 = head2.next
curr = curr.next
curr.next = head1 if head1 else head2
return dummy.next
```
希望我的回答可以帮助到您!
阅读全文