题目
给你一个链表的头节点 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 输出:[]
解题
方法一:双指针
创建一个哑节点,利用pre对cur所在位置的节点删除。
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: dummy = ListNode(0,head) pre=dummy cur=head while cur: if cur.val==val: pre.next =cur.next else: pre=cur cur=cur.next return 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: dummy=cur = ListNode(0,head) while cur.next: if cur.next.val==val: cur.next=cur.next.next else: cur=cur.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) { ListNode* dummy= new ListNode(0,head); ListNode* cur=dummy; while(cur->next!=NULL){ if(cur->next->val==val){ cur->next=cur->next->next; } else{ cur=cur->next; } } return dummy->next; } };
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 { public ListNode removeElements(ListNode head, int val) { ListNode dummy=new ListNode(0); dummy.next=head; ListNode cur=dummy; while(cur.next!=null){ if(cur.next.val==val){ cur.next=cur.next.next; }else{ cur=cur.next; } } return dummy.next; } }