首页 > 编程语言 >算法刷题 Day 3 | 203.移除链表元素 & 707.设计链表 & 206.反转链表

算法刷题 Day 3 | 203.移除链表元素 & 707.设计链表 & 206.反转链表

时间:2022-12-30 19:46:05浏览次数:68  
标签:203 ListNode val int head next 链表 移除

203.移除链表元素

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

Tips:这道题本身没有什么难度,回顾一下链表的定义和虚拟头节点的使用即可

我的题解:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null){
            return head;
        }
        ListNode dummy = new ListNode(-1,head);
        ListNode pre = dummy;
        ListNode current = head;
        while(current!=null){
            if(current.val==val){
                pre.next = current.next;
            }
            else{
                pre = current;
            }
            current = current.next;
        }
        return dummy.next;
    }
}

题目链接/文章讲解/视频讲解::https://programmercarl.com/0203.%E7%A7%BB%E9%99%A4%E9%93%BE%E8%A1%A8%E5%85%83%E7%B4%A0.html

707.设计链表

Tips:这道题先是自己实现了一遍,写的很不优雅,针对测试用例debug了很久,原因有两点:

1. 没有维护一个记录链表大小的变量,导致经常出现null的报错

2. 没有采用一个虚拟头节点,导致逻辑写的比较复杂。

所以参考以上两点重新实现一次,然后就一遍过了

标签:203,ListNode,val,int,head,next,链表,移除
From: https://www.cnblogs.com/GavinGYM/p/17015696.html

相关文章