LeetCode:Palindrome Linked List - 迴文鏈表

一、題目名稱java

Palindrome Linked List(迴文鏈表)node

二、題目地址測試

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

三、題目內容code

英文:Given a singly linked list, determine if it is a palindrome.遞歸

中文:給出一個鏈表,肯定該鏈表是否爲迴文鏈表,即先後對稱的鏈表leetcode

四、解題方法1開發

第一種方式是建立一個逆序的鏈表,而後分別從前向後遍歷正序和逆序兩個鏈表,逐個節點進行比較。get

Java代碼以下:it

/**
 * @功能說明:LeetCode 234 - Palindrome Linked List
 * @開發人員:Tsybius2014
 * @開發時間:2015年12月18日
 */
public class Solution {
    
    /**
     * 測試鏈表是否爲迴文鏈表
     * @param head 鏈表首節點
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        //建立一個逆序的鏈表
        ListNode node = head;
        ListNode tail = null;
        while (node != null) {
            ListNode temp = new ListNode(node.val);
            temp.next = tail;
            tail = temp;
            node = node.next;
        }
        //比對原鏈表與逆序鏈表是否一致
        while (tail != null) {
            if (tail.val != head.val) {
                return false;
            }
            head = head.next;
            tail = tail.next;
        }
        return true; 
    }
}

這個代碼能夠優化一下,即在和建立的逆序鏈表作比較時,之比較一半的節點就能夠了

Java代碼以下:

/**
 * @功能說明:LeetCode 234 - Palindrome Linked List
 * @開發人員:Tsybius2014
 * @開發時間:2015年12月18日
 */
public class Solution {
    
    /**
     * 測試鏈表是否爲迴文鏈表
     * @param head 鏈表首節點
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        //建立一個逆序的鏈表
        ListNode node = head;
        ListNode tail = null;
        int counter = 0;
        while (node != null) {
            ListNode temp = new ListNode(node.val);
            temp.next = tail;
            tail = temp;
            node = node.next;
            counter++;
        }
        counter /= 2;
        //比對原鏈表與逆序鏈表是否一致
        while (counter != 0) {
            counter--;
            if (tail.val != head.val) {
                return false;
            }
            head = head.next;
            tail = tail.next;
        }
        return true; 
    }
}

五、解題方法2

另外一種方式是從討論區看到的方法,這個方法使用遞歸解決本問題,可將空間複雜度控制在O(1)

Java代碼以下:

/**
 * @功能說明:LeetCode 234 - Palindrome Linked List
 * @開發人員:Tsybius2014
 * @開發時間:2015年12月18日
 */
public class Solution {
    
    ListNode temp;
    
    /**
     * 測試鏈表是否爲迴文鏈表
     * @param head 鏈表首節點
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        temp = head;
        return isPalindromeList(head); 
    }
    
    /**
     * 測試鏈表是否爲迴文鏈表
     * @param node 鏈表首節點
     * @return
     */
    private boolean isPalindromeList(ListNode node) {
        if (node == null) {
            return true;
        }
        boolean result = isPalindromeList(node.next) && (temp.val == node.val);
        temp = temp.next;
        return result;
    }
}

END

相關文章
相關標籤/搜索