Total Accepted: 29652 Total Submissions: 117516 Difficulty: Easy
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:
ListNode* reverseList(ListNode* head)
{
ListNode *p=head,*newHead = NULL,*next=NULL;
while(p){
next = p->next;
p->next = newHead;
newHead = p;
p = next;
}
return newHead;
}
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL){
return true;
}
int len = ;
ListNode* p = head;
while(p){
len++;
p=p->next;
}
int m = len/;
p = head;
while(--m){
p=p->next;
}
ListNode *node = p;
if(len%){
p = p->next->next;
ListNode *tmp = node->next;
node->next = NULL;
delete(tmp);
}else{
p = p->next;
node->next = NULL;
}
ListNode *newHead = reverseList(head);
while(newHead && p){
if(newHead->val == p->val){
newHead=newHead->next;
p = p->next;
}else{
return false;
}
}
return true;
// while()
}
};
Next challenges: (E) Palindrome Number (E) Reverse Linked List