题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
# -*- 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
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
newHead = ListNode(None)
cur = newHead
cur1 = pHead1
cur2 = pHead2
while True:
if cur1.val <= cur2.val:
cur.next = cur1
cur = cur1
cur1= cur1.next
if not cur1:
break
else:
cur.next = cur2
cur = cur2
cur2 = cur2.next
if not cur2:
break
if not cur1:
cur.next = cur2
if not cur2:
cur.next = cur1
return newHead.next
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
newHead = ListNode(None)
cur = newHead
cur1 = pHead1
cur2 = pHead2
while True:
if cur1.val <= cur2.val:
cur.next = cur1
cur = cur1
cur1= cur1.next
if not cur1:
break
else:
cur.next = cur2
cur = cur2
cur2 = cur2.next
if not cur2:
break
if not cur1:
cur.next = cur2
if not cur2:
cur.next = cur1
return newHead.next