[LeetCode] Palindrome Linked List

 

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?

 判断回文链表

思路:由于链表无法像数组、字符串一样直接定位到中间索引,所以要利用快慢指针来确定中心元素。再将链表的前半部分的元素放入栈stk中,这时存在一个问题,就是如果链表元素为奇数,则将最中心的元素也放入了stk中,而这个元素不参与之后的比较,所以需要将它弹出stk,如果链表元素为偶数,就不需要对此操作了。接下来依次弹出stk中元素与后半部分元素比较,判断每个对应的元素是否相等,如果不等就返回false。则该链表不是回文链表。

/**
 * 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 == nullptr || head->next == nullptr)
            return true;
        ListNode* fast = head;
        ListNode* slow = head;
        stack<ListNode*> stk;
        stk.push(head);
        while (fast->next != nullptr && fast->next->next != nullptr) {
            fast = fast->next->next;
            slow = slow->next;
            stk.push(slow);
        }
        if (fast->next == nullptr)
            stk.pop();
        while (slow->next != nullptr) {
            slow = slow->next;
            ListNode* tmp = stk.top();
            stk.pop();
            if (tmp->val != slow->val)
                return false;
        }
        return true;
    }
};
// 23 ms

 

 
posted @ 2017-11-03 11:26  immjc  阅读(96)  评论(0编辑  收藏  举报