leetcode刷题记录|203 _移除链表元素


作者 github链接github链接

力扣第203题

类型:链表

题目:

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

示例1

在这里插入图片描述

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

解题思路

思路提醒:三个节点搭配遍历
思路细节:

  1. 定义一个临时节点dummy,放在整个链表的开头(因为head向后移动,链表前面的值就丢失了)
  2. dummy.next指向head
  3. 再定义一个变量prev,负责跟在head后面一个个的保留最后要生成的链表
Created with Raphaël 2.3.0判断head.val是否等于val?prev.next = head.next ;head = head.nextprev = head;head = head.nextyesno
  1. 直到遍历完成,返回 dummy.next

python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if head is None :
            return None
        dummy = ListNode(0)
        dummy.next = head
        prev = dummy
        while(head!=None):
            if head.val == val:
                prev.next = head.next
                head=head.next
            else:
                prev = head
                head = head.next
        return dummy.next

c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(!head) return NULL;
        ListNode * dummy = new ListNode(0);
        dummy -> next = head;
        ListNode * prev=dummy;
        while(head!=NULL){
            if(head->val==val){
                prev->next = head->next;
                head = head->next;
            }
            else{
                prev = head;
                head = head->next;
            }

        }
        return dummy->next;
    }
};

版权声明:本文为weixin_45042017原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。