当前位置: 代码迷 >> 综合 >> Leetcode-移除链表元素
  详细解决方案

Leetcode-移除链表元素

热度:75   发布时间:2024-02-05 05:54:54.0

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 = Noneclass Solution:def removeElements(self, head: ListNode, val: int) -> ListNode:if not head:returnhead.next = self.removeElements(head.next,val)return head.next if head.val == val else head