LeetCode:203. 移除链表元素

简介: 题目描述:给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

🍎道阻且长,行则将至。🍓


🌻算法,不如说它是一种思考方式🍀


算法专栏: 👉🏻123


一、🌱203. 移除链表元素

  • 题目描述:给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
  • 来源:力扣(LeetCode)
  • 难度:简单
  • 提示:

列表中的节点数目在范围 [0, 104]
1 <= Node.val <= 50
0 <= val <= 50

  • 示例:

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

🌾关于链表:

如何构造链表-Node的表示

class listNode{
    int val;
    listNode nextNode;
    public listNode() {
    }
    public listNode(int val) {
        this.val = val;
    }
    public listNode(int val, listNode nextNode) {
        this.val = val;
        this.nextNode = nextNode;
    }
}

-链接

int[] nums = {1,2,6,3,4,5,6};
//构造链表
listNode head=new listNode(nums[0]);
listNode p=head;
for (int i = 1; i < nums.length; i++) {
    listNode q=new listNode(nums[i]);
    p.nextNode=q;
    p=q;
}

-打印链表

p=head;
while(p!=null) {
    System.out.print(p.val+" ");
    p=p.nextNode;
}
System.out.println();

🌴解题

删除一个链表节点只需要修改指针:把前一个元素的指针指向下一个元素。

1.常规链表删除

class Solution {
    publiclistNode removeElements(listNode head, int val) {
        if(head==null)//空链表提前返回
            return head;
        listNode p=head,q=head;

        while (p!=null){//遍历链表
            if(p.val==val){//找到目标元素
                if(p==q){//还是头结点
                    p=p.nextNode;
                    q=q.nextNode;
                    head=head.nextNode;
                }else{
                    q.nextNode=p.nextNode;
                    p=p.nextNode;
                }
            }else{
                q=p;
                p=p.nextNode;
            }
        }
        return head;
    }
}

2.递归删除

class Solution203 {
    public static listNode removeElements(listNode head, int val) {
        if(head==null)
            return head;
        while(head.val==val) {
            head = head.nextNode;
            if(head==null)
                return head;
        }
        head.nextNode=removeElements(head.nextNode,val);
        return head;
    }
}

image.png


返回第一页。☝


☕物有本末,事有终始,知所先后。🍭

相关文章
|
3天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
12 4
|
3天前
leetcode代码记录(下一个更大元素 II
leetcode代码记录(下一个更大元素 II
5 0
|
3天前
|
索引
leetcode代码记录(下一个更大元素 I
leetcode代码记录(下一个更大元素 I
6 0
|
4天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
10 0
|
4天前
leetcode代码记录(移除元素
leetcode代码记录(移除元素
7 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
2月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
2月前
|
存储
LeetCode刷题---817. 链表组件(哈希表)
LeetCode刷题---817. 链表组件(哈希表)
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解