作者 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
输出:[]
解题思路
思路提醒:三个节点搭配遍历
思路细节:
- 定义一个临时节点
dummy
,放在整个链表的开头(因为head
向后移动,链表前面的值就丢失了) dummy.next
指向head
- 再定义一个变量
prev
,负责跟在head后面一个个的保留最后要生成的链表
- 直到遍历完成,返回 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;
}
};