Palindrome Linked List

原创 2015年07月11日 00:34:54

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

Given a singly linked list, determine if it is a palindrome. 题目要求能在O(1)的空间和O(n)的时间内完成。基本思路如下: 1. 找到...

57-Palindrome Linked List

Palindrome Linked List My Submissions QuestionEditorial Solution Total Accepted: 46990 Total Subm...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

Palindrome Linked List

题目地址:https://leetcode.com/problems/palindrome-linked-list/Given a singly linked list, determine if i...

234. Palindrome Linked List(python)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) ti...

LeetCode 之 Palindrome Linked List — C++ 实现

Palindrome Linked List   Given a singly linked list, determine if it is a palindrome. Fol...

[LeetCode-234] Palindrome Linked List(回文链表、链表中间节点查找)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) tim...

LeetCode 234: Palindrome Linked List (回文链表)

Given a singly linked list, determine if it is a palindrome.Follow up:Could you do it in O(n) time a...

Leetcode 234. Palindrome Linked List

234. Palindrome Linked List Total Accepted: 69120 Total Submissions: 225579 Difficulty: Easy ...

(LeetCode 234)Palindrome Linked List

Leetcode第234题目是Palindrome Linked List。题目的描述如下: Given a singly linked list, determine if it is a pali...

234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) ...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)