头图

Niuke.com High-Frequency Algorithm Questions Series-BM13-Determine whether a linked list is a palindrome

Topic description

Given a linked list, please determine whether the linked list is a palindrome.
A palindrome means that the positive and reverse order of the string is exactly the same.

See the original title: BM13 Determine whether a linked list is a palindrome

Solution 1: Linked List Traversal

First of all, consider the special case. If the linked list is empty or there is only one linked list, the default is a palindrome structure and returns true directly.

Otherwise, an additional list is used for processing as follows:

  • Traverse the original linked list and add the values of all nodes in the linked list to a list;
  • Traverse the values in the list to determine whether the linked list is a palindrome. The traversal process is as follows:

    • Traverse the value of 0-list.size()/2 in the list;
    • Determine whether the value of ---4f353e1006fb08157e4a5501385bf013 i and the value of list.size() - i - 1 are equal. If they are not equal, it cannot be a palindrome and returns false directly.
  • After the traversal is completed, if the values of the corresponding positions at the beginning and end of the list are equal, it means that the original linked list is a palindrome structure, and returns true.

code

 import java.util.ArrayList;
import java.util.List;

public class Bm013 {
    /**
     * 判断一个链表是否为回文结构
     *
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public static boolean isPail(ListNode head) {
        // 如果链表为空或只有一个链表,默认是回文结构,返回true
        if (head == null || head.next == null) {
            return true;
        }
        // 遍历链表,将所有结点值放到list中
        List<Integer> nodes = new ArrayList<>();
        while (head != null) {
            nodes.add(head.val);
            head = head.next;
        }
        // 遍历list中的值判断该链表是否是回文结构
        for (int i = 0; i < nodes.size() / 2; i++) {
            // 如果不相等,则不可能是回文结构,直接返回false。
            if (!nodes.get(i).equals(nodes.get(nodes.size() - i - 1))) {
                return false;
            }
        }
        // 遍历完成后,如果list中首尾的相应位置的值都相等,说明原链表是回文结构,返回true。
        return true;
    }

    public static void main(String[] args) {
        ListNode head = ListNode.testCase5();
        System.out.println("原链表为");
        ListNode.print(head);
        System.out.println("是否是回文结构:" + isPail(head));

    }
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!

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

玉树临风,仙姿佚貌!