LeetCodeトップ-100 T234-リストパリンドローム

リストは回文であるかどうかを判断するためにリストを作成します。

例1:

入力: 1 - > 2
 出力: falseに

例2:

入力: 1 - > 2 - > 2 - > 1
 出力: trueに

問題解決のアイデア:

スタックを比較することにより、

コード:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        ListNode cur = head;
        
        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        
        cur = head;
        
        while (cur != null) {
            if (cur.val != stack.pop().val) {
                return false;
            }
            cur = cur.next;
        }
        
        return true;
    }
}

 

おすすめ

転載: blog.csdn.net/qq_41544550/article/details/93240012