您的位置:首页 > 其它

[leetcode] 234. Palindrome Linked List

2016-07-28 12:00 274 查看
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?

解法一:

核心是分别有快慢两个指针,去获取list的中心node的坐标。同时使用一个stack,存储前半段node的数值。这里有一个地方要注意,当list长度是奇数时,slow正好停在正中心。当list长度是偶数时,需要将slow的当前值再push一次。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode* slow = head, *fast = head;
stack<int> vals;

while(fast->next && fast->next->next){
vals.push(slow->val);
slow = slow->next;
fast = fast->next->next;
}
if (fast->next) vals.push(slow->val);

while(slow->next){
if (slow->next->val!=vals.top()) return false;
else{
slow = slow->next;
vals.pop();
}
}

return true;

}
};

解法二:

获得list中心还是一样,然后需要翻转后半段list。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode* slow = head, *fast = head;

while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}

ListNode* cur = slow->next;
while(cur->next){
ListNode* tmp = cur->next;
cur->next = tmp->next;
tmp->next = slow->next;
slow->next = tmp;
}

slow = slow->next;
while(head && slow){
if (head->val != slow->val) return false;
head = head->next;
slow = slow->next;
}

return true;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  easy leetcode