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?
一,算法分析
大体思想是利用快慢两个指针找到中间节点,然后将后面半个链表进行逆转;依次与前半部分比较,若相等则说明是回文串;
二,C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *reverseList(struct ListNode *head){
struct ListNode *p,*q;
p=head->next;
head->next=NULL;
while(p!=NULL){
q=p->next;
p->next=head;
head=p;
p=q;
}
return head;
}
bool isPalindrome(struct ListNode* head) {
struct ListNode *fast,*slow,*middle;
if(head==NULL || head->next==NULL)
return true;
fast=head;
slow=head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
middle = reverseList(slow->next);
slow->next=NULL;//这个非常关键,否则下面的while循环死掉了
while(middle!=NULL && head!=NULL){//这里应该是判断两个,有一个为NULL就停止
if(head->val!=middle->val)
return false;
head=head->next;
middle=middle->next;
}
return true;
}
重要的是一些边界问题的确认,与循环截止条件的设置。