一.解法
https://leetcode-cn.com/problems/remove-linked-list-elements/
要点:链表
Python,C++,Java都用了相同的哨兵法。
用了链表常用的哨兵法,所谓哨兵法指的是在原来链表头前加一个起始节点,保持链表的完整性以免要删除链表头发生错误,再用pre和cur两个指针指向前一个节点和后一个节点,如果cur需要删除,则执行pre.next=cur.next;cur=pre.next;否则pre和cur各自向后移一位。
二.Python实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
newhead=ListNode(0)
newhead.next=head
prev, curr = newhead, head
while curr:
if curr.val == val:
prev.next = curr.next
curr = prev.next
else:
prev = curr
curr = prev.next
return newhead.next
三.C++实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* last,* temp;
ListNode* newhead= new ListNode(0);
newhead->next=head;
last=newhead;
temp=head;
while(temp!=NULL){
if(temp->val==val){
last->next=temp->next;
delete temp;
temp=last->next;
}
else{
last=temp;
temp=last->next;
}
}
return newhead->next;
}
};
四.java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode newhead=new ListNode(0);
newhead.next=head;
ListNode pre=new ListNode(0);
ListNode cur=new ListNode(0);
pre=newhead;
cur=head;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
cur=pre.next;
}
else{
pre=cur;
cur=pre.next;
}
}
return newhead.next;
}
}