题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
两个指针分别指向两个链表,cur指针指向目前已排序好链表的末尾,然后两个指针的node去比,cur指向小的那个,小的那个链表指针后移即可。注意下边界条件就行了。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def Merge(self, pHead1, pHead2):
# write code here
text = ListNode(-1)
cur = text
while pHead1 or pHead2:
if pHead1 == None:
cur.next = pHead2
cur = cur.next
pHead2 = pHead2.next
elif pHead2==None:
cur.next = pHead1
cur = cur.next
pHead1 = pHead1.next
elif pHead1.val <= pHead2.val:
cur.next = pHead1
cur = cur.next
pHead1 = pHead1.next
else:
cur.next = pHead2
cur = cur.next
pHead2 = pHead2.next
return text.next