【Lintcode】223。回文リンクリスト

タイトルアドレス:

https://www.lintcode.com/problem/palindrome-linked-list/description

リンクされたリストが回文かどうかを判別します。

アイデアは、最初にリンクリストの中点を見つけ、次にリンクリストの半分を反転し、最後に2つのリンクリストが等しいかどうかを判断することです(パリティ問題を詳細に検討する必要があります)。コードは次のとおりです。

public class Solution {
    /**
     * @param head: A ListNode.
     * @return: A boolean.
     */
    public boolean isPalindrome(ListNode head) {
        // write your code here
        ListNode dummy = new ListNode(0), slow, fast;
        dummy.next = head;
        slow = fast = dummy;
        // 寻找链表的后半部分的头结点(如果有奇数个节点,则找中间节点的后一个节点)
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode l2 = slow.next;
        slow.next = null;
        return equal(head, reverse(l2));
    }
    
    // 翻转链表
    private ListNode reverse(ListNode head) {
        ListNode res = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = res;
            res = head;
            head = tmp;
        }
        
        return res;
    }
    // 判断两个链表是否相等(如果其中一个链表比另一个链表多一个节点,则只比较除了多出节点的其余节点)
    private boolean equal(ListNode l1, ListNode l2) {
        while (l1 != null && l2 != null) {
            if (l1.val != l2.val) {
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        
        return true;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

時間の複雑さ O(n) 、スペース 1 O(1)

公開された393元の記事 ウォンの賞賛0 ビュー10000 +

おすすめ

転載: blog.csdn.net/qq_46105170/article/details/105468235
おすすめ