解题思路:
首先计算链表长度,然后将链表前半部分利用头插法逆序,与后半部分进行比较
原题目:
Given a singly linked list, determine if it is a palindrome.
AC解,C++代码,菜鸟一个,请大家多多指正
/**
* 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;
int length = 1;
while (p->next != NULL) {
p = p->next;
length++;
}
if (length == 1) {
return true;
}
int count = 2;
p = head->next;
head->next = NULL;
while (count <= (length / 2)) {
ListNode* tmp = p->next;
p->next = head;
head = p;
p = tmp;
count++;
}
if (length % 2 != 0) {
p = p->next;
}
ListNode* q = head;
count--;
while (count > 0) {
if (q->val != p->val) {
return false;
}
q = q->next;
p = p->next;
count--;
}
return true;
}
};