leetcode 234. Palindrome Linked List

来源:互联网 发布:js继承 阮一峰 编辑:程序博客网 时间:2024/05/22 00:36

234. Palindrome Linked List

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?

从中间开始反转链表


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head)     {        if(!head || !head->next)            return head;                    ListNode *last=head;        ListNode *p=last->next;        ListNode *pre=p->next;                while(p)        {            last->next=pre;            p->next=head;            head=p;            p=last->next;            if(p)                pre=p->next;        }        return head;    }    bool isPalindrome(ListNode* head)     {        ListNode *fast = head;        ListNode *slow = head;                while (fast && fast->next)        {            fast = fast->next->next;            slow = slow->next;        }        if (fast)        {            slow->next = reverseList(slow->next);            slow = slow->next;        }        else        {            slow = reverseList(slow);        }        fast = head;        while(fast && slow)        {            if(fast->val != slow->val)                return 0;            fast = fast->next;            slow = slow->next;        }        return 1;    }};


原创粉丝点击