Given a singly linked list, determine if it is a palindrome.

Could you do it in O(n) time and O(1) space?

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//快慢指针找到中点 O(n) O(1)
bool res = true;
while (fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
ListNode *tailFirst = slow;
slow->next = NULL;
//翻转后半部分 O(n) O(1)
//从头逐个比较每个节点 O(n) O(1)
while (p2 != NULL){
if (p1->val != p2->val) {
res = false;
break;
}
p1 = p1->next;
p2 = p2->next;
}
/*恢复链表结构*/
//翻转后半部分组成的链表
//将它连入前半部分链表的最后一个节点
return res;
}
private:
while (p != NULL){
ListNode *pNext = p->next;
p = pNext;
}
}
};

• 本文已收录于以下专栏：

## LeetCode 之 Palindrome Linked List — C++ 实现

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

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。题目的描述如下： Given a singly linked list, determine if it is a pali...

## <LeetCode OJ> 234. Palindrome Linked List

234. Palindrome Linked List My Submissions Question Total Accepted: 33856 Total Submissions: 129...

## leetcode No234. Palindrome Linked List

QuestionGiven a singly linked list, determine if it is a palindrome. 判断链表是否为回文Algorithm需要解决的问题： 1、...