《程式員面試金典》迴文鏈表,《程式員面試金典》
【 聲明:著作權,轉載請標明出處,請勿用於商業用途。 聯絡信箱:libin493073668@sina.com】
題目連結:http://www.nowcoder.com/practice/baefd05def524a92bcfa6e1f113ed4f0?rp=1&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking-the-coding-interview/question-ranking
題目描述
請編寫一個函數,檢查鏈表是否為迴文。
給定一個鏈表ListNode* pHead,請返回一個bool,代錶鏈表是否為迴文。
測試範例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
思路
我們有兩種方法,比較容易想到的方法應該是使用棧儲存前一半的結點,然後對於後一半的結點再一個個的與棧內的結點比較是否相等
還有一種方法就是無需額外開闢空間,我們可以直接將後一串翻轉,然後再兩端比較
1.使用棧
/*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {}};*/class Palindrome{ public: bool isPalindrome(ListNode* pHead) { // write code here if(pHead == nullptr || pHead->next==nullptr) return true; stack<ListNode*> S; ListNode *fast = pHead; ListNode *slow = pHead; while(fast && fast->next) { S.push(slow); fast = fast->next->next; slow = slow->next; } if(fast) slow = slow->next; while(slow) { if(slow->val!=S.top()->val) return false; slow = slow->next; S.pop(); } return true; }};
2.翻轉
/*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {}};*/class Palindrome{ public: bool isPalindrome(ListNode* pHead) { // write code here if(pHead == nullptr || pHead->next==nullptr) return true; ListNode *fast = pHead; ListNode *slow = pHead; while(fast && fast->next) { fast = fast->next->next; slow = slow->next; } if(fast) { slow->next = reverseList(slow->next); slow = slow->next; } else { slow = reverseList(slow); } while(slow) { if(slow->val!=pHead->val) return false; slow = slow->next; pHead = pHead->next; } return true; } ListNode *reverseList(ListNode *pHead) { if(pHead==nullptr) return nullptr; ListNode *pNode = pHead; ListNode *newHead = nullptr; ListNode *pPre = nullptr; while(pNode) { ListNode *pNext = pNode->next; if(pNext==nullptr) newHead = pNode; pNode->next = pPre; pPre = pNode; pNode = pNext; } return newHead; }};
著作權聲明:本文為博主原創文章,如果轉載,請註明出處