2
头图

Palindrome linked list

Title description: Please judge whether a linked list is a palindrome linked list.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/palindrome-linked-list/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Linked list traversal

First, if head is empty or there is only one node, return true directly.

When head is greater than 1 node, first traverse the linked list, use count to record the number of nodes in the linked list as count, then put the first count/2 of the linked list into a stack, and then combine the second half of the nodes in the linked list with the elements in the stack Compare, if there are differences, return false. If they are all the same, return true at the end.

import java.util.Stack;

public class LeetCode_234 {
    public static boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode cur = head;
        // 链表节点的个数
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        // 将前面的一半节点放入栈中
        Stack<Integer> temp = new Stack<>();
        ListNode newCur = head;
        for (int i = 1; i <= count / 2; i++) {
            temp.push(newCur.val);
            newCur = newCur.next;
        }
        int start;
        if (count % 2 == 0) {
            start = count / 2 + 1;
        } else {
            start = count / 2 + 2;
            newCur = newCur.next;
        }
        for (int i = start; i <= count; i++) {
            if (temp.pop() != newCur.val) {
                return false;
            }
            newCur = newCur.next;
        }

        return true;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(0);
        head.next.next = new ListNode(1);

        System.out.println(isPalindrome(head));
    }
}
[Daily Message] People who applaud others are also cheering for their lives.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!