回文链表
題目描述
請編寫一個(gè)函數(shù),檢查鏈表是否為回文。
給定一個(gè)鏈表ListNode*?pHead,請返回一個(gè)bool,代表鏈表是否為回文。
測試樣例: {1,2,3,2,1} 返回:true {1,2,3,2,3} 返回:false分析:對于數(shù)組檢驗(yàn)是否回文是比較容易的。由于單鏈表的特殊性,沒有數(shù)組那么容易操作。這里采用快/慢指針的方法,使的操作減偏 /* struct ListNode {int val;struct ListNode *next;ListNode(int x) : val(x), next(NULL) {} };*/ class Palindrome { public:bool isPalindrome(ListNode* pHead) {ListNode* slow = pHead, *fast = pHead;stack<int> s;
//注意對快指針的邊界判斷!!
while(fast != NULL && fast->next != NULL) {s.push(slow->val);slow = slow->next;fast = fast->next->next; }//奇數(shù)個(gè)元素if(fast != NULL) slow = slow->next;while(slow != NULL) {if (slow->val == s.top()) {slow = slow->next;s.pop();}elsereturn false;}return true;} };
?
轉(zhuǎn)載于:https://www.cnblogs.com/fengcq1129/p/4910779.html
總結(jié)
- 上一篇: JavaScript之三:jQuery插
- 下一篇: windows内核中杀任意进程,可杀36