leetcode 234. 回文链表(Palindrome Linked List)

题目描述:

请判断一个链表是否为回文链表。

示例 1:

    输入: 1->2
    输出: false

示例 2:

    输入: 1->2->2->1
    输出: true

进阶:

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

解法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head){
        if(!head || !head->next){
            return head;
        }else{
            ListNode* cur = head, * nxt = head->next;
            head->next = NULL;
            while(nxt){
                cur = nxt;
                nxt = nxt->next;
                cur->next = head;
                head = cur;
            }
            return head;
        }
    }
    
    bool isPalindrome(ListNode* head) {
        if(!head || !head->next){
            return true;
        }else{
            int sz = 0;
            ListNode* cur = head;
            while(cur){
                sz++;
                cur = cur->next;
            }
            int half = (sz + 1)/2;
            cur = head;
            for(int i = 1; i < half; i++){
                cur = cur->next;
            }
            ListNode* rh = cur->next;
            cur->next = NULL;
            rh = reverse(rh);
            cur = head;
            while(cur && rh && cur->val == rh->val){
                cur = cur->next;
                rh = rh->next;
            }
            return rh == NULL;
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10571211.html
今日推荐