题目来源:leetcode
Question: 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?
首先回文链表是什么意思?
是指,链表的逆序和正序一模一样。
例: {5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5}是回文序列
代码如下:
/**
* 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) { //in O(n) time and O(1) space
if (head == NULL || head->next == NULL) //空链表或单节点链表
{
return true;
}
bool result = false;
int listLen = 0;
for (ListNode *pNode = head; pNode != NULL; pNode = pNode->next)
{
++listLen;
}
ListNode *pPre = NULL;
ListNode *pCur = head;
ListNode *pNext = head->next;
for (int i=0; i<listLen/2; ++i) //一分为二,左边链表逆序,右边链表不变
{
pCur->next = pPre;
pPre = pCur;
pCur = pNext;
pNext = pNext->next;
}
ListNode *pLeftHead = pPre;
ListNode *pRightHead = pCur;
if (listLen & 1) //若是奇数,不比较中间数
{
pRightHead = pRightHead->next;
}
while (pLeftHead != NULL) //左右链表逐个遍历,如果全部相等,才是回文
{
if(pLeftHead->val != pRightHead->val)
{
result = false;
break;
}
pLeftHead = pLeftHead->next;
pRightHead = pRightHead->next;
}
if (pLeftHead == NULL)
{
result = true;
}
//还原链表结构
pLeftHead = pPre;
pRightHead = pCur;
pPre = pRightHead;
pCur = pLeftHead;
pNext = pLeftHead->next;
for (int i=0; i<listLen/2; ++i)
{
pCur->next = pPre;
pPre = pCur;
pCur = pNext;
if (pNext != NULL)
{
pNext = pNext->next;
}
}
return result;
}
};