由于本人跨专业,数据结构基础较为薄弱,写这道题的时候参考了discussion区的答案,把答案读明白了,做了标注,现在这儿简单记录一下,这道题主要是要了解一下链表的基本机构以及指向是通过node1.next=node2这种赋值语句来做的,所谓排序就是在2个list当中找一个升序的指向,最后返回的是p1所以要在最后对p1先为空的情况进行判断。有空系统写一下python链表的相关知识以及常见习题类型和复杂度分析。
21. Merge Two Sorted Lists
Easy
1960271FavoriteShare
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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:#l1 not exists
return l2
if not l2:#l2 not exists
return l1
if l1.val>=l2.val:
l1,l2=l2,l1
p1=l1
p2=l2
head=l1
while p1.next and p2:#不进入循环:只要p1.next和p2有一个是null
if p1.next.val<=p2.val:
p1=p1.next
continue#p1.next<= p2,skip,next
p1Next=p1.next
p2Next=p2.next
p1.next=p2#箭头顺序改变
p2.next=p1Next
p1,p2=p2,p2Next
if p2:#假如p1先走完的话,把p2加进去,但如果p2先走完的话无所谓,因为要把p2放进p1里,所以只看p2空的时候
p1.next=p2
return l1
Success
Runtime: 36 ms, faster than 23.12% of Python online submissions for Merge Two Sorted Lists.
Memory Usage: 10.8 MB, less than 56.08% of Python online submissions for Merge Two Sorted Lists.