首页 > 其他 > 详细

Palindrome Linked List

时间:2015-07-25 19:39:23      阅读:188      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!