簡體   English   中英

盡管對我來說一切都很好,但為什么我的一段代碼表現得很奇怪

[英]Why is my piece of code behaving weird although when everything seems fine to me

我在 Leetcode https://leetcode.com/problems/palindrome-linked-list/上解決了這個簡單的問題,並被我的解決方案卡住了。 這里是,

class Solution {
   public:
   bool isPalindrome(ListNode* head)
   {
       stack <int> st;
       ListNode *slow=head,*fast=head;
       while(fast!=NULL && fast->next!=NULL)
       {
           st.push(slow->val);
           slow=slow->next;
           fast=fast->next->next;
       }
       if(fast==NULL)
           st.pop();
       while(slow!=NULL && !st.empty())
       {
           if(slow->val!=st.top())
               return 0;
           st.pop();
           slow=slow->next;
       }
       return 1;
   }
};

雖然我有其他幾種方法,但很想知道這段代碼不起作用的原因......謝謝!

您在這里遵循的想法很聰明。 我首先將整個列表推入堆棧,將其還原並比較原始堆棧和還原堆棧。 有效,但可能是最壞的情況。

您試圖找到中間值並僅將輸入的前半部分記錄在堆棧中。 然后繼續向前走並向后比較堆棧。

你的問題:

  1. fast前進而不檢查下一個指針是否非 null。
  2. 您必須根據fast->next是 null 還是fast->next->next是 null 來處理 TOS。 如果fast->next是null,你有奇數個元素,中間元素是TOS,所以必須去掉。 否則,堆棧上有偶數個值,您必須直接開始與 TOS 進行比較。

由於這可能是家庭作業,我將把實際的實現留給你。

對於該任務的后續:此搜索是 O(n) 時間,但我認為不是 O(1) 空間,因為堆棧大小取決於元素的數量。 不知道如何在沒有堆棧的情況下做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM