力扣第203题
类型:链表题目:
示例1示例2示例3解题思路 pythonc++
作者 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输出:[]
解题思路 思路提醒:三个节点搭配遍历
思路细节:
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass 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++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; }};