【每日一题】【链表or双指针循环条件】2022年2月26日-NC96 判断一个链表是否为回文结构


描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。

思路:

public boolean isPail (ListNode head) {
    ListNode node = head;
    LinkedList list = new LinkedList<>();
    while (node != null) {
        list.addLast(node.val);
        node = node.next;
    }
    while (list.size()>1) {
        if (!list.removeFirst().equals(list.removeLast())) {
            return false;
        }
    }
    return true;
}

或者以数组形式取

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
         
        // 将链表元素放到数组
        ArrayList arr = new ArrayList();
        ListNode cur = head;
        while(cur!=null){
            arr.add(cur.val);
            cur = cur.next;
        }
        // 数组双指针判断回文
        int i=0;
        int j=arr.size()-1;
        while(i<=j){       
                if((arr.get(i)).equals(arr.get(j))){
                    i++;
                    j--;
                }else{
                    return false;
                }
 
        }
        return true;
         
    }
}