LeetCode 题解(186): Palindrome Linked List

题目:

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

题解:

O(1)space需要in-place的reverse后半拉list,然后比较,用两个指针找到后半拉的起始位置。

C++版:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return true;
        ListNode* s = head, *f = head;
        while(f->next != NULL && f->next->next != NULL) {
            f = f->next->next;
            s = s->next;
        }
        s->next = reverse(s->next);
        s = s->next;
        ListNode* p = head;
        while(s != NULL) {
            if(s->val != p->val)
                return false;
            s = s->next;
            p = p->next;
        }
        return true;
    }
    
    ListNode* reverse(ListNode* root) {
        if(root->next == NULL)
            return root;
        ListNode* newRoot = reverse(root->next);
        root->next->next = root;
        root->next = NULL;
        return newRoot;
    }
};

Java版:

public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null)
            return true;
        ListNode s = head, f = head;
        while(f.next != null && f.next.next != null) {
            s = s.next;
            f = f.next.next;
        }
        s.next = reverse(s.next);
        s = s.next;
        ListNode p = head;
        while(s != null) {
            if(s.val != p.val)
                return false;
            s = s.next;
            p = p.next;
        }
        return true;
    }
    
    public ListNode reverse(ListNode root) {
        if(root.next == null)
            return root;
        ListNode newRoot = reverse(root.next);
        root.next.next = root;
        root.next = null;
        return newRoot;
    }
}

Python版:

class Solution:
    # @param {ListNode} head
    # @return {boolean}
    def isPalindrome(self, head):
        if head == None or head.next == None:
            return True
        fast, slow = head, head
        while fast.next != None and fast.next.next != None:
            fast = fast.next.next
            slow = slow.next
        slow.next = self.reverse(slow.next)
        slow = slow.next
        p = head
        while slow != None:
            if slow.val != p.val:
                return False
            slow = slow.next
            p = p.next
        return True
        
    def reverse(self, head):
        if head.next == None:
            return head
        newHead = self.reverse(head.next)
        head.next.next = head
        head.next = None
        return newHead

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值