目录
21.合并两个有序链表
思路:
1.常规遍历:对于两个链表当中的元素,分别取出对比,较小的作为新链表的下一个元素,较大的留作下次比较,如果有一个链表提前到达空,则直接将另一个链表的剩余部分链接到新链表之后
2.递归:终止条件是两个链表都为空,每次递归时,把下一次递归的结果链接到当前较小节点之后
代码:
1.非递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
p = list1
q = list2
r = ListNode(0)
head = r
while (p or q):
x = p.val if p else 1000 #不存在用个很大的数代替
y = q.val if q else 1000
if y >= x: # 不一定都存在 需要进行判断
r.next = ListNode(x)
p = p.next if p else 0
r = r.next
else:
r.next = ListNode(y)
q = q.next if q else 0
r = r.next
return head.next
2.递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2 # 终止条件,直到两个链表都空
if not l2: return l1
if l1.val <= l2.val: # 递归调用
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
206.反转链表
206. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)
思路:
1.使用额外空间:对链表进行一次遍历,每次都取出当前元素并添加到新链表的头部
2.python3语法糖:多元赋值,在等号左边对当前节点和下一节点进行修改,使得当前节点的后继节点为当前节点的前置节点,这点在py当中很容易实现,首先设置pre=None,p=head,再在每个循环当中设置pre, pre.next = p, pre并将p后移即可
3.递归:终止条件是链表为空或者head.next为空,通过递归找到链表的尾节点,然后依次修改节点head.next.next = head 并修改当前节点的下一个节点为None防止形成循环链表
代码:
1.使用额外空间
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return head
p = head
q = None
while p:
q = ListNode(p.val ,q)
p = p.next
return q
2.python3语法糖
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p, cur = head, None
while p:
cur, cur.next, p = p, cur, p.next
return cur
3.递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
cur = self.reverseList(head.next) # 直接head.next.next直到最后一个
head.next.next = head # 设置head的下一位的下一位是自己
head.next = None
return cur