Leetcode21题
主要实现:创建节点--创建2个单链表- 链表合并
1、创建单链表节点类
class ListNode:
def __init__(self,val = 0, next = None):
self.val = val
self.next = next
2、两个有序链表创建(使用尾插法)
l1 = [1,2,4]
l2 = [1,3,4]
head1 = ListNode(0)
head2 = ListNode(0)
cur1 = head1
cur2 = head2
# 单链表1
for i in range(len(l1)):
list1 = ListNode(l1[i])
cur1.next = list1
cur1 = cur1.next
#单链表2
for j in range(len(l2)):
list2 = ListNode(l2[j])
cur2.next = list2
cur2 = cur2.next
3、合并这两个链表
class Solution:
def mergeTwoLists(self,list1,list2):
prehead = ListNode(-1)
pre = prehead
while list1 and list2:
if list1.val <= list2.val:
pre.next = list1
list1 = list1.next
else:
pre.next = list2
list2 = list2.next
pre = pre.next
if list1 is not None and list2 is None:
pre.next = list1
elif list1 is None and list2 is not None:
pre.next = list2
return prehead.next
4 完整程序
class ListNode:
def __init__(self,val = 0, next = None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self,list1,list2):
prehead = ListNode(-1)
pre = prehead
while list1 and list2:
if list1.val <= list2.val:
pre.next = list1
list1 = list1.next
else:
pre.next = list2
list2 = list2.next
pre = pre.next
if list1 is not None and list2 is None:
pre.next = list1
elif list1 is None and list2 is not None:
pre.next = list2
return prehead.next
if __name__ == "__main__":
l1 = [1,2,4]
# l1 = []
l2 = [1,3,4]
head1 = ListNode(0)
head2 = ListNode(0)
cur1 = head1
cur2 = head2
for i in range(len(l1)):
list1 = ListNode(l1[i])
cur1.next = list1
cur1 = cur1.next
for j in range(len(l2)):
list2 = ListNode(l2[j])
cur2.next = list2
cur2 = cur2.next
# solu = Solution()
ans = Solution().mergeTwoLists(head1.next,head2.next)
while ans != None:
print(ans.val,end='')
ans = ans.next