LintCode 223: Palindrome Linked List

  1. Palindrome Linked List
    Implement a function to check if a linked list is a palindrome.

Example
Example 1:

Input: 1->2->1
output: true
Example 2:

Input: 2->2->1
output: false
Challenge
Could you do it in O(n) time and O(1) space?

解法1:
我用的stack。
注意:
1)奇数和偶数,midIndex都是len/2 - 1。
但奇数的midIndex要从midIndex后面2个开始。
2) 求链表的中点也可以用快慢指针法。
代码如下:

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: A ListNode.
     * @return: A boolean.
     */
    bool isPalindrome(ListNode * head) {
        if (!head || !head->next) return true;
        
        int len = 0;
        ListNode * p = head;
        while(p) {
            len++;
            p = p->next;
        }
        
        //1->2->1, midIndex = 0;
        //1->2->2->1, midIndex = 1;
        int midIndex = len / 2 - 1; 
        
        stack<int> s;
        p = head;
        
        for (int i = 0; i <= midIndex; ++i) {
            s.push(p->val);
            p = p->next;
        }
        if (len & 0x1) p = p->next; //1->2->1, p points to the 2nd 1
 
        while(p) {
            if (p->val == s.top()) {
                p = p->next;
                s.pop();
            } else {
                return false;
            }
        }

        return true;
    }
};

解法2:
空间O(1)的算法就是把后半段链表反转后看是不是和前半段链表相等。TBD。

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: A ListNode.
     * @return: A boolean.
     */
    bool isPalindrome(ListNode *head) {
        if (!head || !head->next) return true;
        ListNode *fast = head, *slow = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode *newHead = reverseLinkedList(slow);
        while (head && newHead) {
            if (head->val != newHead->val) return false;
            head = head->next;
            newHead = newHead->next;
        }
        return true;
    }
private:
    ListNode * reverseLinkedList(ListNode *node) {
        ListNode *pre = NULL;
        while (node) {
            ListNode *tmp = node->next;
            node->next = pre;
            pre = node;
            node = tmp;
        }
        return pre;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值