每日一题:Leetcode203 移除链表元素

简介: 每日一题:Leetcode203 移除链表元素

题目描述

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


示例 1:

c53add94697c48b6bc5795495f9f4c17.jpg


输入: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
输出:[]


提示:

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


思路

两种思路;使用虚拟头节点和不使用虚拟头节点。两种方式的共同思路是:首先定义变量,然后通过遍历链表,如果该节点的值等于要删除的值,就使前一个节点的下一个节点等于该节点的下一个节点,从而实现链表中数据的删除


java参考代码

/**
 * 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 {
    //添加虚拟节点方式 时间复杂度O(n) 空间复杂度O(1)
 public ListNode removeElements(ListNode head, int val) {
        if(head == null){
            return head;
        }
        ListNode dummy = new ListNode(-1,head);
        ListNode pre = dummy;
        ListNode cur = head;
        while(cur != null){
            if(cur == val){
                pre.next = cur.next;
            }else{
                pre = cur;
            }
            cur = cur.next;
        }
        return dummy.next;
    }
    public ListNode removeElements(ListNode head, int val) {
        while(head != null && head.val == val){
            head = head.next;
        }
        ListNode curr = head;
        while(curr!= null){
            while(curr.next != null && curr.next.val ==val){
                curr.next = curr.next.next;
            }
            curr = curr.next;
        }
        return head;
    }
}


go参考代码:

go中需要自己实现结构体的定义

 type ListNode struct {
      Val int
     Next *ListNode
 }
func removeElements(head *ListNode,val int) *ListNode {
  dummyHead := &ListNode{}
  dummyHead.Next = head
  cur := dummyHead
  for cur!= nil && cur.Next != nil{
    if cur.Next.Val == val{
      cur.Next = cur.Next.Next
    }else{
      cur = cur.Next
    }
  }
  return dummyHead.Next
}

以上分析,希望对您有所帮助,您的支持是我最大的动力,感谢一键三连!!

相关文章
|
4月前
【力扣】-- 移除链表元素
【力扣】-- 移除链表元素
48 1
|
4月前
Leetcode第21题(合并两个有序链表)
这篇文章介绍了如何使用非递归和递归方法解决LeetCode第21题,即合并两个有序链表的问题。
62 0
Leetcode第21题(合并两个有序链表)
|
4月前
【LeetCode 27】347.前k个高频元素
【LeetCode 27】347.前k个高频元素
49 0
|
4月前
LeetCode第二十四题(两两交换链表中的节点)
这篇文章介绍了LeetCode第24题的解法,即如何通过使用三个指针(preNode, curNode, curNextNode)来两两交换链表中的节点,并提供了详细的代码实现。
35 0
LeetCode第二十四题(两两交换链表中的节点)
|
4月前
Leetcode第十九题(删除链表的倒数第N个节点)
LeetCode第19题要求删除链表的倒数第N个节点,可以通过快慢指针法在一次遍历中实现。
52 0
Leetcode第十九题(删除链表的倒数第N个节点)
|
4月前
|
索引
力扣(LeetCode)数据结构练习题(3)------链表
力扣(LeetCode)数据结构练习题(3)------链表
114 0
|
4月前
【LeetCode 10】142. 环形链表 II
【LeetCode 10】142. 环形链表 II
31 0
|
4月前
【LeetCode 09】19 删除链表的倒数第 N 个结点
【LeetCode 09】19 删除链表的倒数第 N 个结点
23 0
|
4月前
【LeetCode 08】206 反转链表
【LeetCode 08】206 反转链表
19 0
|
4月前
【LeetCode 06】203.移除链表元素
【LeetCode 06】203.移除链表元素
40 0