您的位置:首页 > 编程语言 > C语言/C++

LeetCode 234. Palindrome Linked List

2016-03-09 01:03 295 查看
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;
}


重要的是一些边界问题的确认,与循环截止条件的设置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息