LeetCode小白菜笔记[7]:Merge Two Sorted Lists
来源:互联网 发布:部队网络安全教育 编辑:程序博客网 时间:2024/06/09 19:03
LeetCode小白菜笔记[7]:Merge Two Sorted Lists
21. Merge Two Sorted Lists [Easy]
题目: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->4Output: 1->1->2->3->4->4
这道题的目的是将两个排好序的链表合并成一个并且还保持有序的性质。一个简单的想法就是在两个链表上各设置一个初始值在表头的可以移动的标签,两个游标所指向的元素比较大小,小的一个就加入Merged List,并把该游标后移一个。这样会移动到直到该游标所指的大于另一个所指的,然后另一个游标就变成了移动的,这样交替,就可以 Merge 两个有序链表了。
代码如下:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 == None: return l2 if l2 == None: return l1 merged = ListNode(0) thisnode = ListNode(0) merged.next = thisnode thisnode1 = l1 thisnode2 = l2 while True : if (thisnode1.val < thisnode2.val): # compare the values thisnode.next = thisnode1 # add smaller one to merge list thisnode1 = thisnode1.next # shift the added tag by 1 thisnode = thisnode.next # merge list forward else : thisnode.next = thisnode2 thisnode2 = thisnode2.next thisnode = thisnode.next if (thisnode.next == None): break if (thisnode1 == None): thisnode.next = thisnode2 else: thisnode.next = thisnode1 return merged.next.next
结果如下:
总结:
- 开始时submission没有通过,由于没有考虑空链表的特殊情况。
- 对于while何时停止,开始时用两个链表其中一个到头就停止,发现结果错误,因为最末的数字根本没有参与计算和比较,于是考虑当merged链表的next指向None时停止,并且把剩下的没比较的直接接上(因为必然比merged当前的尾节点的数字要大,否则就应该在前面)。但是从上面的code可以看出 thisnode初始化的时候next就是None,因此应先进while再判断,应该用do~while语句,python中用 while True ~ if (condition) : break 代替。
- 对于涉及到指针的操作还不熟悉,需要加强。
THE END
2017/12/16 Sat 01:24 a.m.
阅读全文
0 0
- LeetCode小白菜笔记[7]:Merge Two Sorted Lists
- leetcode笔记:Merge Two Sorted Lists
- leetcode笔记--Merge Two Sorted Lists
- leetcode笔记:Merge Two Sorted Lists
- LeetCode笔记:21. Merge Two Sorted Lists
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- CORS跨域-Nginx使用方法(Access-Control-Allow-Origin错误提示)
- c3p0的相关配置说明
- Deep Learning实战之word2vec
- 关于递推平均分几块问题
- 数组去重
- LeetCode小白菜笔记[7]:Merge Two Sorted Lists
- 生成器是特殊的迭代器?
- ajax 下拉框连动选择省市县
- React-Native Android环境搭建
- 从0到1搭建spark集群---企业集群搭建
- IT行业近年风投业简析
- 基于springboot搭建dubbo框架(注解和xml配置两种方式)
- 一位资深程序员大牛给予Java初学者的学习建议
- Java了解