面试题 02.06. 回文链表

面试题 02.06. 回文链表
编写一个函数,检查输入的链表是否是回文的。

示例 1:

输入: 1->2
输出: false 

示例 2:

输入: 1->2->2->1
输出: true 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *slow = head, *fast = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        // ListNode *cur = slow->next;
        ListNode *pre = NULL;
        ListNode *next;
        while(slow != NULL){
            next = slow->next;
            slow->next = pre;
            pre = slow; 
            slow = next;
        }
        while(pre && head){
            if(pre->val == head->val){
                pre = pre->next;
                head = head->next;
            } else {
                return false;
            }
        }
        return true;

    }
};

你可能感兴趣的:(程序员面试经典,链表,面试,java)