LeetCode 之 Palindrome Linked List — C++ 实现

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

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

根据要求，需要在原链表上进行操作。可以将链表前半部分翻转，然后再和后半部分进行比较。

class Solution {
public:
bool isPalindrome(ListNode* head) {
{
return true;
}

ListNode *pre = NULL, *ne = NULL;//pre指向已经反转好的头节点
ListNode *phalf = head, *p = head;
bool ovenNode = false;//判断节点数是偶数还是奇数
while(p->next) //找出中间节点，并将前一半节点翻转
{
ne = phalf;
phalf = phalf->next;
p = p->next;
if(p->next)//p移动两次，phalf移动一次
{
p = p->next;
}
else
{
ovenNode = true;
}

{
}
else
{
ne->next = pre; //翻转
pre = ne;
}

}

if(!ovenNode) //奇数个节点，跳出中间节点不比较
{
phalf = phalf->next;
}

while(phalf) //回文检测
{
if(pre->val != phalf->val)
{
return false;
}
phalf = phalf->next;
pre = pre->next;
}

return true;
}
};

【leetcode】234. Palindrome Linked List（Python & C++）

2017-09-02 20:15:34

LeetCode 234: Palindrome Linked List （回文链表）

2015-07-16 22:48:30

234. Palindrome Linked List [easy] (Python)

2016-05-03 19:09:18

2015-07-29 11:40:29

Leetcode:234. Palindrome Linked List(JAVA)

2016-03-16 21:19:03

2015-07-10 09:33:38

LeetCode--234. Palindrome Linked List

2016-03-05 21:34:54

LeetCode 206. Reverse Linked List 题解（C++）

2016-10-23 16:18:19

234. Palindrome Linked List（python）

2016-09-18 21:45:15

LeetCode 141 — Linked List Cycle（C++ Java Python）

2014-02-27 21:26:32