234. 回文链表

46 阅读1分钟

题目描述:

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

image.png

题解思路1:使用栈的方式

1、首先将链表中的元素都放进入栈中,然后从栈中弹出和链表的头一个一个的比较,如果有一个不同则不会回文链表。这种方式显然不是最优解,最优解后续更新。。。。。。

public static boolean isPalindrome(ListNode head) {

    if (head == null || head.next == null){
        return true;
    }
    Stack<Integer> stack = new Stack<>();
    ListNode cur = head;
    while(cur!=null){
        stack.push(cur.val);
        cur = cur.next;
    }
    cur = head;
    while(!stack.isEmpty()){
        if (!stack.pop().equals(cur.val)){
            return false;
        }
        cur = cur.next;
    }
    return true;
}