题目:
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解答:
把ListNode理解为一种新的数据类型,不可迭代,但有.next方法,(其实就是C语言数据结构里面的链表)
.next执行过之后结果就没了,所以用temp作为一个中间结果,总体上temp == result,temp在获取值的时候.next用掉了,但是result的结果依然完整
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode(0)
temp = result
while l1 and l2:
if(l1.val<l2.val):
temp.next = l1;
l1 = l1.next
temp = temp.next
else:
temp.next = l2;
l2 = l2.next
temp = temp.next
while l1:
temp.next = l1;
l1 = l1.next
temp = temp.next
while l2:
temp.next = l2;
l2 = l2.next
temp = temp.next
return result.next