lintcode-回文链表

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

/**
 * 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;
    }
};
    原文作者:鬼谷神奇
    原文地址: https://www.jianshu.com/p/e9fd0c403575#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞