最近在学习链表,感觉链表确实难。自己还需要加强练习,先做了一道leetcode的题,不是自己做的,是参考的别人的:[(https://zhidao.baidu.com/question/458258273283753765.html)
我只是添加了一丁点,感觉这个写的稍微有些冗余,但是自己又不知道咋改。
先上代码吧:
'''
@greg 2017-09-02
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.
'''
class ListNode(object):
'''
定义一个节点
'''
def __init__(self, val):
self.val = val
self.next = None
def LinkedList(pythonList):
'''
传入一个普通列表,生成一个链表
:param pythonList:
:return:
'''
if len(pythonList) == 0: # 空列表直接返回None,这样合并时对于空的链表就好处理了
return None
p = ListNode(pythonList[0]) # 定义链表的头,c指向这个头,c相当于一个动态的指针
c = p
for i in range(1, len(pythonList)):
c.next = ListNode(pythonList[i])
c = c.next
return p
def PythonList(ListNode):
'''
传入一个链表,转换为普通的python列表
:param ListNode:
:return:
'''
l = []
p = ListNode
while p is not None:
l.append(p.val)
p = p.next
return l
class Solution(object):
def mergeTwoLists(self, l1, l2):
newLinkedList = ListNode(0)
p = newLinkedList
if None in (l1, l2): # 其中一个为None,就返回另一个
return l1 or l2
# l1和l2是一个链表,而且指向链表的头部
# 这一段是比较两个节点的数值大小,小的就放入新的链表中,并分别指向下一个节点
while l1 is not None and l2 is not None:
if l1.val < l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next # p指向当前节点
# 这大地方的目的是为了将剩余的节点存进新的链表,比如说,上面l1.val
# 和l2.val分别为最后一个节点,加入我们只存储了l1,还有l2
# 没有存进来,此时l1已经是None,我们直接把l2存到最后就可以了,
# 因为l1和l2的大小已经比过了。
if l1 is not None:
p.next = l1
else:
p.next = l2
return newLinkedList.next
if __name__ == '__main__':
l1 = LinkedList([])
l2 = LinkedList([])
s = Solution()
print(PythonList(s.mergeTwoLists(l1, l2)))
# print([] is not None)