您的位置:首页 > 其它

2.6 Palindrome

2015-10-27 06:46 197 查看
1. Reverse and Compare:

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


2. Using extra space ( stack)

bool isPalindrome(ListNode* head){
stack<int> stk;
if(!head || !head->next) return true;
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
stk.push(slow->val);
fast = fast->next->next;
slow = slow->next;
}
if(fast) slow = slow->next;//if the list has odd length we skip middle point;
while(slow || !stk.empty()){
if(slow->val != stk.top()) return false;
slow = slow->next;
stk.pop();
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LinkedList