日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode-移除链表元素

發布時間:2025/3/15 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode-移除链表元素 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

?

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。