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?

/**
 * 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 == NULL)
        {
            return true;
        }
        ListNode *p = head;
	    ListNode *q = head;
	    while (p->next && p->next->next)
	    {
		    p  = p->next->next;
		    q = q->next;
	    }
	    ListNode *midNode = q;
	    ListNode *secondHead = revert(midNode);
	
	    p = head;
	    q = secondHead;
	    while (p != NULL)
	    {
		    if (p->val != q->val)
		    {
			    return false;
		    }
		    p = p->next;
		    q = q->next;
	    }

	    revert(midNode);
	    return true; 
    }
private:
    ListNode* revert(ListNode *head)
    {
	    ListNode *p = head->next;
	    ListNode *q = head;
	    while (p != NULL)
	    {
		    ListNode *r = p->next;
		    p->next = q;
		    q = p;
		    p = r;
	    }

	    head->next = NULL;
	    return q;
    }
};


阅读更多
个人分类: 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Palindrome Linked List

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭