代码随想录 Day3 | Leetcode203 移除链表元素、Leetcode707 设计链表、Leetcode206反转链表

代码随想录系列

1.代码随想录Day1
2.代码随想录Day2


上题

1.203 移除链表元素 - 力扣(LeetCode)
2.707 设计链表 - 力扣(LeetCode)
3.206 反转链表 - 力扣(LeetCode)


一、第一题

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

示例 1:

1->2->6->3->4->5->6
    |
1->2->3->4->5

输入:head = [1, 2, 6, 3, 4, 5, 6], val = 6
输出:[1, 2, 3, 4, 5]

示例 2:

输入:head = [], val = 1
输出:[]

示例 3:

输入:head = [7, 7, 7, 7], val = 7
输出:[]

1.思路

链表基本操作,需要掌握怎么定义链表结构,力扣都是帮忙定义好的

2.代码

class ListNode:
    # 定义结点
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


class Solution:
    """
    给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

    示例 1:
    1->2->6->3->4->5->6
        |
    1->2->3->4->5

    输入:head = [1,2,6,3,4,5,6], val = 6
    输出:[1,2,3,4,5]

    示例 2:
    输入:head = [], val = 1
    输出:[]

    示例 3:
    输入:head = [7,7,7,7], val = 7
    输出:[]
    """
    def removeElements(self, head: ListNode, val):
        """
        链表基本用法罢了,需要记得结点怎么定义
        """
        # 先处理头结点,如果头节点等于预期值,就把头指针后移
        while head and head.val == val:
            head = head.next

        # 头节点处理完再判断是否全空了,比如[7, 7, 7, 7]
        if not head:
            return

        pre = head
        while pre.next:
            if pre.next.val == val:
                pre.next = pre.next.next
            else:
                pre = pre.next
        return head


if __name__ == '__main__':
    test = Solution()
    heads = [[1, 2, 6, 3, 4, 5, 6], [], [7, 7, 7, 7]]
    val = [6, 1, 7]

    for i in range(len(heads)):
        head = ListNode(None)
        for j in heads[i][::-1]:
            a = ListNode(j)
            a.next = head.next
            head.next = a

        test_head = test.removeElements(head, val[i])
        # pre = test_head
        result = []
        while test_head and test_head.next:
            result.append(test_head.next.val)
            test_head = test_head.next
        print(result)

二、第二题

你可以选择使用单链表或者双链表,设计并实现自己的链表。
单链表中的节点应该具备两个属性:val 和 next 。val 是当前节点的值,next 是指向下一个节点的指针/引用。
如果是双向链表,则还需要属性 prev 以指示链表中的上一个节点。假设链表中的所有节点下标从 0 开始。

实现 MyLinkedList 类:
MyLinkedList() 初始化 MyLinkedList 对象。
int get(int index) 获取链表中下标为 index 的节点的值。如果下标无效,则返回 -1 。
void addAtHead(int val) 将一个值为 val 的节点插入到链表中第一个元素之前。在插入完成后,新节点会成为链表的第一个节点。
void addAtTail(int val) 将一个值为 val 的节点追加到链表中作为链表的最后一个元素。
void addAtIndex(int index, int val) 将一个值为 val 的节点插入到链表中下标为 index 的节点之前。如果 index 等于链表的长度,那么该节点会被追加到链表的末尾。如果 index 比长度更大,该节点将 不会插入 到链表中。
void deleteAtIndex(int index) 如果下标有效,则删除链表中下标为 index 的节点。

示例:

输入
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
输出
[null, null, null, null, 2, null, 3]

解释
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
myLinkedList.get(1);              // 返回 2
myLinkedList.deleteAtIndex(1);    // 现在,链表变为 1->3
myLinkedList.get(1);              // 返回 3

1.思路

链表操作文章诸多,不多赘述,既然是练习,尽量不使用类内方法,一个一个码。。。。注意审题,第一个数(非头结点)下标是从0开始的

2.代码

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


class MyLinkedList:
    """
    你可以选择使用单链表或者双链表,设计并实现自己的链表。

    单链表中的节点应该具备两个属性:val 和 next 。val 是当前节点的值,next 是指向下一个节点的指针/引用。

    如果是双向链表,则还需要属性 prev 以指示链表中的上一个节点。假设链表中的所有节点下标从 0 开始。

    实现 MyLinkedList 类:
    MyLinkedList() 初始化 MyLinkedList 对象。
    int get(int index) 获取链表中下标为 index 的节点的值。如果下标无效,则返回 -1 。
    void addAtHead(int val) 将一个值为 val 的节点插入到链表中第一个元素之前。在插入完成后,新节点会成为链表的第一个节点。
    void addAtTail(int val) 将一个值为 val 的节点追加到链表中作为链表的最后一个元素。
    void addAtIndex(int index, int val) 将一个值为 val 的节点插入到链表中下标为 index 的节点之前。如果 index 等于链表的长度,那么该节点会被追加到链表的末尾。如果 index 比长度更大,该节点将 不会插入 到链表中。
    void deleteAtIndex(int index) 如果下标有效,则删除链表中下标为 index 的节点。

    示例:

    输入
    ["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
    [[], [1], [3], [1, 2], [1], [1], [1]]
    输出
    [null, null, null, null, 2, null, 3]

    解释
    MyLinkedList myLinkedList = new MyLinkedList();
    myLinkedList.addAtHead(1);
    myLinkedList.addAtTail(3);
    myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
    myLinkedList.get(1);              // 返回 2
    myLinkedList.deleteAtIndex(1);    // 现在,链表变为 1->3
    myLinkedList.get(1);              // 返回 3
    """

    def __init__(self):
        self.size = 0
        self.head = ListNode(None)

    def get(self, index):
        pre = self.head
        while index < 0 or index >= self.size:
            return -1
        for _ in range(index+1):
            pre = pre.next
        return pre.val

    def addAtHead(self, val):
        # 可以先写addAtAtIndex再直接调用
        pre = self.head
        pre_node = ListNode(val)
        pre_node.next = pre.next
        pre.next = pre_node
        self.size += 1

    def addAtTail(self, val):
        pre = self.head
        pre_node = ListNode(val)
        while pre.next:
            pre = pre.next
        pre.next = pre_node
        self.size += 1

    def addAtIndex(self, index, val):
        if index > self.size:
            return
        pre = self.head
        pre_node = ListNode(val)
        i = 0
        while i < index:
            pre = pre.next
            i += 1
        pre_node.next = pre.next
        pre.next = pre_node
        self.size += 1

    def deleteAtIndex(self, index):
        if index >= self.size:
            return
        pre = self.head
        i = 0
        while i < index:
            pre = pre.next
        pre.next = pre.next.next
        self.size -= 1


if __name__ == '__main__':
    test = MyLinkedList()
    test_head = test.head
    for i in range(5, 0, -1):
        a = ListNode(i)
        a.next = test.head.next
        test.head.next = a
        test.size += 1
    # test.addAtHead(6)
    # test.addAtTail(6)
    # test.addAtIndex(0, 'a')
    # test.deleteAtIndex(1)
    print(test.get(1))

三、第三题

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]

1.思路

正好复习双指针。。。。

cur = head	//cur指向头结点
pre = None	//pre指向....是空气吧
tem = cur.next	//tem保存cur的下一个值
大致结构:(这里借用leetcode一个小哥的截图,学习之用,侵删。。。。一两点还在码,懒得画了)

在这里插入图片描述

下面开始反转
cur.next = pre	//头节点指向尾结点末,指针方向转向
pre = cur	//pre保存cur当前的值,下一次循环cur指向它
cur = tem	//cur变成原先保存的下一个值

(乱七八糟,越写越羡慕文章写得好的人)

2.代码

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


class Solution:
    def reverseList(self, head):
        """
         给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

        示例 1:
        输入:head = [1,2,3,4,5]
        输出:[5,4,3,2,1]

        示例 2:
        输入:head = [1,2]
        输出:[2,1]

        示例 3:
        输入:head = []
        输出:[]
        """
        cur = head
        pre = None
        while cur:
            tem = cur.next
            cur.next = pre
            pre = cur
            cur = tem

        return pre


if __name__ == '__main__':
    test = Solution()
    heads = [[1, 2, 3, 4, 5], [1, 2], []]
    for i in heads:
        result = []
        if len(i) == 0:
            print(result)
            continue
        head = ListNode(i[0])
        for j in i[-1:0:-1]:
            a = ListNode(j)
            a.next = head.next
            head.next = a
        test_head = test.reverseList(head)
        while test_head:
            result.append(test_head.val)
            test_head = test_head.next
        print(result)

总结

未来的你一定会感谢现在学习的你

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值