代码随想录算法训练营第三天 | 203.移除链表元素、707. 设计链表、206.反转链表

203.移除链表元素

题目链接:https://leetcode.cn/problems/remove-linked-list-elements/

文章讲解:代码随想录

视频讲解:手把手带你学会操作链表 | LeetCode:203.移除链表元素_哔哩哔哩_bilibili

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        # Remove from the beginning if head has the value val
        dummy_head = ListNode(next=head)
        p = dummy_head
        while p.next:
            if p.next.val == val:
                p.next = p.next.next
            else:
                p = p.next
        return dummy_head.next

主要学习一下用伪节点的写法

注意要返回的dummy.next,不是p.next;熟悉python语言的链表表示和判断非空的方式

707. 设计链表

题目链接:https://leetcode.cn/problems/remove-linked-list-elements/description/

文章讲解:代码随想录

视频讲解:帮你把链表操作学个通透!LeetCode:707.设计链表_哔哩哔哩_bilibili

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

    def __init__(self):
        self.dummy_head = ListNode()
        self.size = 0

    def get(self, index: int) -> int:
        if index < 0 or index >= self.size:
            return -1
        p = self.dummy_head.next
        for i in range(index):
            p = p.next
        return p.val

    def addAtHead(self, val: int) -> None:
        self.dummy_head.next = ListNode(val, self.dummy_head.next)
        self.size += 1

    def addAtTail(self, val: int) -> None:
        p = self.dummy_head
        while p.next:
            p = p.next
        p.next = ListNode(val)
        self.size += 1

    def addAtIndex(self, index: int, val: int) -> None:
        if index < 0 or index > self.size:
            return
        
        p = self.dummy_head
        for i in range(index):
            p = p.next
        p.next = ListNode(val, p.next)
        self.size += 1

    def deleteAtIndex(self, index: int) -> None:
        if index < 0 or index >= self.size:
            return
        
        p = self.dummy_head
        for i in range(index):
            p = p.next
        p.next = p.next.next
        self.size -= 1


# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)

注意对index输入的判别

206.反转链表

题目链接:https://leetcode.cn/problems/reverse-linked-list/description/

文章讲解:代码随想录

视频讲解:帮你拿下反转链表 | LeetCode:206.反转链表 | 双指针法 | 递归法_哔哩哔哩_bilibili

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        cur = head
        pre = None
        while cur:
            temp = cur.next 
            cur.next = pre
            pre = cur
            cur = temp
        return pre

第一次有点路径依赖了,还是想写伪头节点,后来发现并不合适

然后递归的做法还没有太理解...

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值