Day3 (1/1/2024) - LeetCode #203,#707,#206

本文介绍了如何在LeetCode中的链表题目中运用虚拟头结点技巧,包括移除指定值的元素、反转链表以及设计包含添加、删除功能的链表。通过实例展示了链表操作的关键步骤和注意事项。
摘要由CSDN通过智能技术生成

 203.移除链表元素  

建议: 本题最关键是要理解 虚拟头结点的使用技巧,这个对链表题目很重要。

题目链接/文章讲解/视频讲解::代码随想录

Notes:

1. create a new listNode dummy and point the next pointer of head

2. create a new listNode cur and set it to dummy.

3. loop through cur.next ( Highlight here: 1.  why not loop from head? The reason is never loop head, but instead loop a new created dummy node 2. Why not set cur to head but set cur to dummy? This is because if traverse from head, if the last node is equal to the val, it won't be disconnected).

- Summary, loop starts from dummy.next while cur.next != null 

    public ListNode removeElements(ListNode head, int val) {
        if(head==null) return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
    
        ListNode cur = dummy;
        while (cur.next != null) {

            if(cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
            cur = cur.next;
            }
        }

    

        return dummy.next;
    }

 707.设计链表  

建议: 这是一道考察 链表综合操作的题目,不算容易,可以练一练 使用虚拟头结点

题目链接/文章讲解/视频讲解:代码随想录

 

LeetCode - The World's Leading Online Programming Learning Platform

Notes:

1. create a ListNode class with int val, next pointer and constructor.

2. Maintain instance variable size and a head node in MyLinkedList. 

3. MylinkedList constructor, default head node with val 0, not null( Here not understand);

4. Write addAtIndex method first, then use it for addAtHead, and addAtTail. 

5. Everytime add a node or remove a node, update size vairable correspondingly.

 206.反转链表 

建议先看我的视频讲解,视频讲解中对 反转链表需要注意的点讲的很清晰了,看完之后大家的疑惑基本都解决了。

题目链接/文章讲解/视频讲解:代码随想录

Notes: ( 复习👆文章里的动画) —— Hightlight : change the direction of the pointer.

首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。

然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。

为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。

接下来,就是循环走如下代码逻辑了,继续移动pre和cur指针。

最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。 此时我们return pre指针就可以了,pre指针就指向了新的头结点

        ListNode prev = null;

        ListNode cur = head;

        ListNode temp = null;

        while(cur!=null) {

            temp = cur.next;

            cur.next = prev;

            prev = cur;

            cur = temp;

        }

        return prev;

       

  • 21
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值