# 234. Palindrome Linked List

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

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

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head) {
int i,j=0;
int* p=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)                          //将链表的数据顺序存储
{
}
for(i=0;i<n/2;i++)                        //回文检测
{
if(*(p+i)==*(p+n-1-i))
j++;
else
break;
}
return j==n/2?true:false;
}
{
int length=1;
return 0;
{
length++;
}
return length;
}

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode *head) {
int n,i,j=0;
struct ListNode *middle,*p,*s,*t;
middle=(struct ListNode*)malloc(sizeof(struct ListNode));
middle->val=9;
if(n<2)                                  //链表长度小于2
return true;
else if(n==2)
else if(n==3)
else
{
for(i=0;i<n/2-1;i++)                 //寻找中间节点前一个节点
p=p->next;
if(n%2==0)                           //偶数个节点
middle->next=p->next;
else
middle->next=p->next->next;
p->next=NULL;

/*后半部分链表反转*/
p=middle->next;
s=p->next;
p->next=NULL;
while(s)
{
t=s->next;
s->next=p;
p=s;
s=t;
}
middle->next=p;

/*回文判断*/
s=middle->next;
while(p!=NULL)
{
if(p->val==s->val)
{
p=p->next;
s=s->next;
j++;
}
else
break;
}
return j==n/2?true:false;
}
}

{
int length=1;
length=0;
else
{
length++;
}
return length;
}

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode *head) {
int n,i,j=0;
struct ListNode *middle,*p,*s,*t;
if(n<2)                                   //链表长度小于2
return true;
else if(n==2)                             //链表长度等于2
else if(n==3)
else
{
for(i=0;i<n/2-1;i++)                  //寻找中间节点前一个节点
p=p->next;
middle=n%2==0?p->next:p->next->next;  //根据节点奇偶情况为middle指针
p->next=NULL;                         //前半链表最后一个节点next指向NULL

/*后半部分链表反转*/
p=middle;
s=p->next;
p->next=NULL;
while(s)
{
t=s->next;
s->next=p;
p=s;
s=t;
}
middle=p;                           //middle作为后半段链表的头指针

/*回文判断*/
s=middle;
while(p)
{
if(p->val==s->val)
{
p=p->next;
s=s->next;
j++;
}
else
break;
}
return j==n/2?true:false;
}
}

{
int length=1;
length=0;
else
{
length++;
}
return length;
}

05-03 2299

03-16 567

07-16 1.3万

09-18 510

09-02 627

07-29 3866

06-30 58

01-16 406

01-08 122

05-22 105