【LeetCode】234. Palindrome Linked List
生活随笔
收集整理的這篇文章主要介紹了
【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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 视频直播美颜sdk的发展史
- 下一篇: 从分歧到共识:疫情下的5G发展思考