题目
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?
思路
此题比较简单,具体思路如下:
将一个链表分成两半,然后将后面这个链表进行翻转,最后就对这两个链表从后到尾进行比较即可。
struct ListNode * reverseList(struct ListNode *head){
if(head==NULL){
return NULL;
}
struct ListNode * cur=head;
struct ListNode * pre=NULL;
struct ListNode * next=NULL;
while(cur!=NULL){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
bool isPalindrome(struct ListNode* head) {
if(head==NULL){
return true;
}
struct ListNode * cur=head;
struct ListNode* pre=NULL;
int len=0;
while(cur!=NULL){
len++;
cur=cur->next;
}
if(len==1){
return true;
}
cur=head;
int k=len/2;
while(k>0){
pre=cur;
cur=cur->next;
k--;
}
struct ListNode *newhead=cur;
pre->next=NULL;
cur=head;
struct ListNode * otherHead=reverseList(newhead);
struct ListNode * cur1=otherHead;
int tempLen=len/2;
while(cur!=NULL){
int temp1=cur->val;
int temp2=cur1->val;
if(temp1!=temp2){
return false;
}
cur=cur->next;
cur1=cur1->next;
}
return true;
}