面试题 02.06. 回文链表

面试题 02.06. 回文链表

编写一个函数,检查输入的链表是否是回文的。

示例 1:

输入: 1->2
输出: false 

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

思路:因为要求空间复杂度O(1), 所以需要找出链表终点,用一个快指针和一个慢指针,快指针每次跑2步,慢指针每次跑1步, 遍历的时候顺便把前半部分链表颠倒。最后判前后两个断链表是否值是否相同。

/**
 * 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) {
        if(head==NULL || head->next==NULL) return true;
        if(head->next->next==NULL) return head->val == head->next->val;//只有两个数
        //找中点并且翻转前面的链表
        ListNode *pre=NULL, *cur=NULL, *nex=head;
        while(head->next && head->next->next){
            head = (head->next)->next;
            cur = nex;
            nex = cur->next;
            cur->next = pre;
            pre = cur;
        }
        if(head->next!=NULL){//再多走一步
            cur = nex;
            nex = cur->next;
            cur->next = pre;
            pre = cur;
        }
        else{
            nex = nex->next;
        }
        while(cur && nex){
            if(cur->val!=nex->val) return false;
            cur = cur->next;
            nex = nex->next;
        }
        return true;
    }
};

 

上一篇:[bzoj2245]工作安排


下一篇:[BZOJ1009] [HNOI2008] GT考试(KMP+dp+矩阵快速幂)