您的位置:首页 > 其它

算法设计与应用基础系列19

2017-06-16 23:08 274 查看

Palindrome Linked List

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

class
Solution {

public:

    bool isPalindrome(ListNode* head) {

        if(head==NULL||head->next==NULL)

            return true;

        ListNode* slow=head;

        ListNode* fast=head;

        while(fast->next!=NULL&&fast->next->next!=NULL){

            slow=slow->next;

            fast=fast->next->next;

        }

        slow->next=reverseList(slow->next);

        slow=slow->next;

        while(slow!=NULL){

            if(head->val!=slow->val)

                return false;

            head=head->next;

            slow=slow->next;

        }

        return true;

    }

    ListNode* reverseList(ListNode* head) {

        ListNode* pre=NULL;

        ListNode* next=NULL;

        while(head!=NULL){

            next=head->next;

            head->next=pre;

            pre=head;

            head=next;

        }

        return pre;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: