【剑指offer】合并两个排序的链表(python)
一开始的想法是将两个链表都放到一个数组里,排序后再建成一个链表,但是python列表不能对两个链表节点进行大小比较,所以还是用传统思路,依次比较两个链表节点的大小,接到答案链表里,最后剩下的部分直接接上。
# -*- 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 List = [] if pHead1 is None: if pHead2 is None: return None else: return pHead2 p1 = pHead1 p2 = pHead2 head = ListNode(0) pre = head while p1 and p2: if p1.val <= p2.val: pre.next = p1 p1 = p1.next else: pre.next = p2 p2 = p2.next pre = pre.next if p1: pre.next = p1 if p2: pre.next = p2 return head.next