本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/03/target-offer-merge-linked-list.html 作者: Suixin
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
生成一个新的结点,将两个链表的结点依次链在后面。比较时,使用两个指针,始终把小的那个链到新链表中,指针后移,直到至少一方到链表末尾为止,再把未到达末尾的那个链表链接上来即可。最终返回最开始生成的结点的下一个结点。
代码
Python(2.7.3)
此处对于空链表的特殊输入已经包含于代码中。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
newHead = ListNode(1)
cur = newHead
while pHead1 is not None and pHead2 is not None:
if pHead1.val <= pHead2.val:
cur.next = pHead1
pHead1 = pHead1.next
else:
cur.next = pHead2
pHead2 = pHead2.next
cur = cur.next
if pHead1 is not None:
cur.next = pHead1
elif pHead2 is not None:
cur.next = pHead2
return newHead.next
运行时间:30ms
占用内存:5724k
参考
https://www.nowcoder.com/profile/649003/codeBookDetail?submissionId=9009620