C 设置哨兵节点,常规解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//prev->next= curr->next
/*
设置一个哨兵节点,作为第一个节点的前驱节点,然后循环判断即可,不过最后要记得释放哨兵节点,否则会
超出时间限制的
*/
struct ListNode* removeElements(struct ListNode* head, int val){
if(!head){
return NULL;
}
//设置一个节点,是第一个节点的前驱节点
struct ListNode *first = malloc(sizeof(struct ListNode));
first->next = head;
struct ListNode *prev=first,*curr=head;
while(curr!=NULL){
if(curr->val == val){
prev->next = curr->next;
}else{
prev = curr;
}
curr = curr->next;
}
head = first->next;
free(first);//释放内存,要不然会超出时间限制
return head;
递归方法
链表 一般都是具有天然的递归性
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/*
递归 来判断 链表
*/
struct ListNode* removeElements(struct ListNode* head, int val){
if(!head){
return NULL;
}
//直到到达链表尾部才开始删除重复元素
head->next = removeElements(head->next,val);
return head->val == val?head->next:head;
}
C++ 迭代方法
直接循环判断,最后再来判断head节点是否等于val值
/**
* 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) {
if(!head){
return NULL;
}
struct ListNode *p =head,*q;
while(p->next){
if(p->next->val==val){
p->next=p->next->next;
}else{
p=p->next;
}
}
return head->val == val?head->next:head;
}
};
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:
if not head:return
head.next = self.removeElements(head.next,val)
return head.next if head.val == val else head