首页 > 其他 > 详细

203. 移除链表元素

时间:2021-08-30 05:15:18      阅读:17      评论:0      收藏:0      [点我收藏+]

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

技术分享图片

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

Constraints:

  • The number of nodes in the list is in the range [0, 104].
  • 1 <= Node.val <= 50
  • 0 <= k <= 50

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

 

解题思路:

借助dummy node。

这个题用 dummy node 的用意在于包括 head 节点在内,都有可能是需要被删除的点,

使得从头节点就是要删除的节点和中间要删除的,可以用相同的处理方式

 

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null){
            return head;
        }
    
        ListNode cur=new ListNode(0);
        ListNode curHead=cur;
        cur.next=head;
        while(cur.next!=null){
         if(cur.next.val==val){
             cur.next=cur.next.next;
         }else{
             cur=cur.next;
         }
         
        }

        return curHead.next;

    }
}

  

 

 

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null)
            return head;

        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head; 
    }
}

  

 

 

 

 

 

 

 

 

203. 移除链表元素

原文:https://www.cnblogs.com/iwyc/p/15200877.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!