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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

【LeetCode】234. Palindrome Linked List

發布時間:2024/3/26 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】234. Palindrome Linked List 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

Subscribe to see which companies asked this question


思路

我的思路

想了半天沒有想出空間為1的解法,就用了最先考慮到的數據結構棧來實現了。首先定義兩個快慢指針,從頭開始遍歷,將慢指針壓進棧內,當快指針走到尾時,慢指針指向的就確定了中間位置。然后慢指針繼續前進,同時和棧頂元素進行比較,如果不相等則返回false。

Hot 解法

開始都是使用快慢指針確定了中間位置,然后它實現了一個翻轉鏈表的操作,將慢指針還未走過的鏈表翻轉了,然后對翻轉的鏈表和從頭開始的鏈表進行比較。


代碼

我的代碼

bool isPalindrome(ListNode* head) {if (!head) return true;stack<ListNode*> st;ListNode* fast=head;ListNode* slow=head;while (fast&&fast->next){st.push(slow);fast=fast->next->next;slow=slow->next;}if (fast) slow=slow->next;while (!st.empty() && slow->val==st.top()->val){st.pop();slow=slow->next;}return st.empty();}

Hot解法

bool isPalindrome(ListNode* head) {if(head==NULL||head->next==NULL)return true;ListNode* slow=head;ListNode* fast=head;while(fast->next!=NULL&&fast->next->next!=NULL){slow=slow->next;fast=fast->next->next;}slow->next=reverseList(slow->next);slow=slow->next;while(slow!=NULL){if(head->val!=slow->val)return false;head=head->next;slow=slow->next;}return true;}ListNode* reverseList(ListNode* head) {ListNode* pre=NULL;ListNode* next=NULL;while(head!=NULL){next=head->next;head->next=pre;pre=head;head=next;}return pre;}

鏈表翻轉

鏈表翻轉就是一道比較經典的題目,此處是一個O(1)的實現。最重要最需要注意的兩個地方是提前保存下一個節點(next)和保存翻轉后的頭結點(prev)。

ListNode* reverseList(ListNode* head) {ListNode* pre=NULL;ListNode* next=NULL;while(head!=NULL){next=head->next;head->next=pre;pre=head;head=next;}return pre;}

記憶小技巧:在while循環里一共四句話,最開始當然是要提前保存正常順序下的下一個節點,可以發現它們都是收尾相接的,最后移動head到保存好的next節點。

總結

以上是生活随笔為你收集整理的【LeetCode】234. Palindrome Linked List的全部內容,希望文章能夠幫你解決所遇到的問題。

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