已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。 输入格式: 输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
时间: 2024-03-16 18:36:44 浏览: 119
输入非降序列,转换成非升序列,合并成一个非升序列
我可以为您提供一个解决方案来合并两个非降序链表S1和S2,构造出新的非降序链表S3。
以下是一个Python实现的示例代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_sorted_lists(s1, s2):
dummy = ListNode(-1) # 创建一个虚拟头结点
curr = dummy
while s1 and s2:
if s1.val <= s2.val:
curr.next = s1
s1 = s1.next
else:
curr.next = s2
s2 = s2.next
curr = curr.next
# 将剩余的节点接到合并链表的末尾
if s1:
curr.next = s1
if s2:
curr.next = s2
return dummy.next
# 读取输入序列
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
# 创建链表并合并
head1 = ListNode(s1[0])
curr1 = head1
for num in s1[1:]:
curr1.next = ListNode(num)
curr1 = curr1.next
head2 = ListNode(s2[0])
curr2 = head2
for num in s2[1:]:
curr2.next = ListNode(num)
curr2 = curr2.next
merged_head = merge_sorted_lists(head1, head2)
# 打印合并后的链表S3
result = []
curr = merged_head
while curr:
result.append(curr.val)
curr = curr.next
print(*result)
```
阅读全文