lintcode-回文链表

作者: 鬼谷神奇 | 来源:发表于2016-06-21 14:54 被阅读39次

    设计一种方式检查一个链表是否为回文链表。
    再用原地反转解决一次

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        /**
         * @param head a ListNode
         * @return a boolean
         */
        
        ListNode * reverseList(ListNode * head) {
            
            ListNode * p = head;
            head = NULL;
            
            while(p) {
                ListNode * q = p;
                p = p->next;
                q->next = NULL;
                q->next = head;
                head = q;
                
            }
            
            return head;
        }
        
        void print(ListNode * head) {
            while(head) {
                cout << head->val << " ";
                head = head->next;
            }
            
            cout << endl;
            
        }
         
        bool isPalindrome(ListNode* head) {
            // Write your code here
            if(head == NULL || head->next == NULL) {
                return true;
            }
            
            ListNode * slow = head, * fast = head;
            while(fast && fast->next) {
                slow = slow->next;
                fast = fast->next->next;
            }
            
            if(fast) {
                
                slow = reverseList(slow->next);
                //print(slow->next);
                
            } else {
                
                slow = reverseList(slow);
                //print(slow);
                
                
            }
            
            while(slow) {
                if(head->val != slow->val) {
                    return false;
                }
                
                head = head->next;
                slow = slow->next;
            }
            
            return true;
        }
    };
    

    相关文章

      网友评论

        本文标题:lintcode-回文链表

        本文链接:https://www.haomeiwen.com/subject/zzdgdttx.html