刷力扣热题–第二十一天:2.两数相加 + 24.两两交换链表中的节点
菜鸟第二十一天开始奋战敲代码,持之以恒,见证成长
1.题目简介
(1)两数相加
(2)两两交换链表中的节点
2.题目解答
(1)两数相加
即将两个链表两两相加,遇到需要进位的,进位符置1,直到两个链表全都遍历完成.
(2)两两交换链表中的节点
遵循三个原则:不论长短的单双数,开始的指针指向中间的,中间的指向头的,更新开始的指针为头的,头的指向最后的,头的指针更新为最后的,中间的为头的下一个,最后的中间的下一个,而开始的指针的下一个为中间的~感觉这里肯定是存在情况,还没想好怎么改正 ~
3.心得体会
现在要开始不仅锻炼写作能力,逻辑性一定也要强,增强代码的可读性~
(1)两数相加 代码略显冗余
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
list_node = ListNode()
head = list_node
carry_character = 0
while True:
if l1 is None and l2 is None:
if carry_character:
temp = ListNode()
temp.val = carry_character
temp.next = None
list_node.next = temp
return head.next
if l1 is None and l2 is not None:
if carry_character:
sum_value = l2.val + carry_character
if sum_value >= 10:
temp = ListNode()
temp.val = sum_value % 10
temp.next = None
carry_character = 1
else:
temp = ListNode()
temp.val = sum_value
temp.next = None
carry_character = 0
list_node.next = temp
list_node = list_node.next
l2 = l2.next
else:
list_node.next = l2
return head.next
if l1 is not None and l2 is None:
if carry_character:
sum_value = l1.val + carry_character
if sum_value >= 10:
temp = ListNode()
temp.val = sum_value % 10
temp.next = None
carry_character = 1
else:
temp = ListNode()
temp.val = sum_value
temp.next = None
carry_character = 0
list_node.next = temp
list_node = list_node.next
l1 = l1.next
else:
list_node.next = l1
return head.next
if l1 is not None and l2 is not None:
sum_value = l1.val + l2.val + carry_character
if sum_value >= 10:
temp = ListNode()
temp.val = sum_value % 10
temp.next = None
carry_character = 1
else:
temp = ListNode()
temp.val = sum_value
temp.next = None
carry_character = 0
list_node.next = temp
list_node = list_node.next
l1 = l1.next
l2 = l2.next
(2)两两交换链表中的节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
if head.next is None:
return head
start = head
medium = start.next
head = medium
temp = head
end = medium.next
if end is None:
temp.next = start
start.next = None
return temp
while True:
medium.next = start
start.next = end
head = start
start = end
if start is None:
break
if start.next is None:
break
medium = start.next
head.next = medium
end = medium.next
return temp
4.做题时长
7月28日 22:00-22:40 22:50-23:17 有在进步就行了~