代码随想录Day3 | LeetCode 203. 移除链表元素、LeetCode 707. 设计链表、LeetCode 206. 反转链表

LeetCode 203. 移除链表元素

链表基础概念题,也可以用递归做,不过我们把递归的思想放在更能体现它的LeetCode 206.反转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        if not head:
            return head
        dummy = ListNode()
        dummy.next = head
        p = dummy
        while p and p.next:
            if p.next.val == val:
                p.next = p.next.next
            else:
                p = p.next
        return dummy.next

LeetCode 707.设计链表

同样是基础的链表操作,注意定义一个ListNode类

class ListNode:
    def __init__(self, val = 0, next = None):
        self.val = val
        self.next = next     

LeetCode 206.反转链表

递归

# 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: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        new_head = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return new_head
posted @ 2024-09-17 23:00  溺死在幸福里的猪  阅读(9)  评论(0)    收藏  举报