码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Linked List

时间:2015-07-25 19:40:11      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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?

  这题思路就是把单链表的前半部分或后半部分反转,然后比较。

solution:

bool isPalindrome(ListNode* head) {
    if (head == NULL || head->next == NULL)
        return true;

    ListNode *fast = head;
    ListNode *slow = head;
    while (fast->next != NULL)
    {
        fast = fast->next;
        slow = slow->next;
        if (fast->next != NULL)
            fast = fast->next;
    }
    fast = reverseList(slow);
    ListNode *p = head;
    while (p != slow && p->val == fast->val)
    {
        p = p->next;
        fast = fast->next;
    }
    if (p == slow)
        return true;
    else
        return false;
}

反转单链表的代码见这里

Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/gattaca/p/4676365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!