日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Leetcode-移除链表元素

發(fā)布時(shí)間:2025/3/15 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode-移除链表元素 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

C? 設(shè)置哨兵節(jié)點(diǎn),常規(guī)解法

/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*///prev->next= curr->next /* 設(shè)置一個(gè)哨兵節(jié)點(diǎn),作為第一個(gè)節(jié)點(diǎn)的前驅(qū)節(jié)點(diǎn),然后循環(huán)判斷即可,不過最后要記得釋放哨兵節(jié)點(diǎn),否則會(huì) 超出時(shí)間限制的 */ struct ListNode* removeElements(struct ListNode* head, int val){if(!head){return NULL;}//設(shè)置一個(gè)節(jié)點(diǎn),是第一個(gè)節(jié)點(diǎn)的前驅(qū)節(jié)點(diǎn)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);//釋放內(nèi)存,要不然會(huì)超出時(shí)間限制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;}//直到到達(dá)鏈表尾部才開始刪除重復(fù)元素head->next = removeElements(head->next,val);return head->val == val?head->next:head; }

C++ 迭代方法?

直接循環(huán)判斷,最后再來判斷head節(jié)點(diǎn)是否等于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

?

總結(jié)

以上是生活随笔為你收集整理的Leetcode-移除链表元素的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。