Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题目意思很简单,就是合并两个有序链表,头需要是原先的两个链表中的一个。这道题在本科生的数据结构书上就有讲,原理就就是:两个链表A,B分别逐个遍历,判断两个元素的大小,取小的作为新链表的下一个节点。让小学生做,他们也能知道原理,但是这里我是用python写的,调试了好久才得到结果,主要的原因就出在python本身的机制上。先贴代码,再细说:
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param two ListNodes # @return a ListNode def mergeTwoLists(self, l1, l2): p1 = l1 p2 = l2 if l1 == None: return l2 if l2 == None: return l1 if l1.val < l2.val: #print 'choose:1' h = ListNode(l1.val) hm = h while(p1.next != None and p2 != None): #print p1.val,p2.val if p1.next.val > p2.val: tempnode = ListNode(p2.val) #注意,此处需要注意,不要使用赋值语句,使用赋值语句你就完了! h.next = tempnode h = tempnode p2 = p2.next else: tempnode = ListNode(p1.next.val) h.next = tempnode h = h.next p1 = p1.next print h.val if p1.next == None: #l1遍历完了 h.next = p2 else: h.next = p1.next return hm else: #print 'choose:2' h = ListNode(l2.val) hm = h while(p1 != None and p2.next != None): if p2.next.val > p1.val: tempnode = ListNode(p1.val) h.next = tempnode h = tempnode p1 = p1.next else: tempnode = ListNode(p2.next.val) h.next = tempnode h = h.next p2 = p2.next print h.val if p1 == None: #l1遍历完了 h.next = p2.next else: h.next = p1 return hm
最主要的问题就出在新链表h的构建问题上,起初,我用的不是:
tempnode = ListNode(p2.val) h.next = tempnode h = tempnode
而是使用的:
h.next = p1.next h = h.next
这就造成了一个指针的混乱,原因就出在python的拷贝机制上。python的拷贝机制有三种,例子如下:
import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b = a #赋值,传对象的引用 c = copy.copy(a) #对象拷贝,浅拷贝 d = copy.deepcopy(a) #对象拷贝,深拷贝 a.append(5) #修改对象a a[4].append('c') #修改对象a中的['a', 'b']数组对象
b.append(1) print 'a = ', a print 'b = ', b print 'c = ', c print 'd = ', d 结果如下: a = [1, 2, 3, 4, ['a', 'b', 'c'], 5, 1] b = [1, 2, 3, 4, ['a', 'b', 'c'], 5, 1] c = [1, 2, 3, 4, ['a', 'b', 'c']] d = [1, 2, 3, 4, ['a', 'b']]
我之前所用的复制方式,就是采用的第一种,将新链表和P1关联起来,这样,一旦h发生改变之后,p1也发生了改变。造成了指针的混乱,所以我这次采用的方式是:对于新链表,每次要添加一个元素的时候,就新建一个节点,把要添加的元素的值赋值给它,这样就不会发生混乱了。