首页 > 其他 > 详细

【LeetCode】234. Palindrome Linked List

时间:2019-10-23 15:14:17      阅读:66      评论:0      收藏:0      [点我收藏+]

Difficulty:easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/palindrome-linked-list/

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

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

Intuition

Mehtod 1. reverse the right half of the list

Method 2. use a stack to store

 

Solution

    //Method 1: reverse half of the list
    public boolean isPalindrome(ListNode head) {
        if(head==null)
            return true;
        ListNode slow = head, fast = head;
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        if(fast!=null) // odd nodes: let right half smaller
            slow = slow.next;
        slow = reverse(slow);
        while(slow!=null){
            if(head.val != slow.val)
                return false;
            head=head.next;
            slow=slow.next;
        }
        return true;
    }
    
    public ListNode reverse(ListNode node){
        ListNode pre = null;
        ListNode cur = node;
        while(cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    
    
    //Method 2: use a stack to store
    public boolean isPalindrome1(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        ListNode node = head;
        while(node!=null){
            stack.push(node);
            node=node.next;
        }
        while(!stack.isEmpty()){
            if(head.val != stack.pop().val)
                return false;
            head=head.next;
        }
        return true;
    }

  

Complexity

Method 1: (it will modify the original list)

Time complexity : O(n)

Space complexity : O(1)

 

Method 2:

Time complexity : O(n)

Space complexity : O(n)

 

 More:【目录】LeetCode Java实现

 

【LeetCode】234. Palindrome Linked List

原文:https://www.cnblogs.com/yongh/p/11726283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!