111 判断一个链表是否为回文结构
Table of Contents

ac

  1. 利用辅助栈
  2. 反转左边一半,同时得到右边一半下标(注意奇偶),然后两个链表一起遍历判断即可
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;


class Node{
    int val;
    Node next;

    public Node(int val) {
        this.val = val;
        this.next = null;
    }
}

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        int n = sc.nextInt();
        Node head = new Node(-1);
        Node tail = head;
        for(int i=0;i<n;i++){
            int val = sc.nextInt();
            if(i == 0){
                head.val = val;
                tail = head;
            }else {
                Node newNode = new Node(val);
                tail.next = newNode;
                tail = newNode;
            }
        }
        System.out.println(isRev(head) ? "true" : false);
    }

    static boolean isRev(Node head){
        int nodeCnt = 0;
        Node p = head;
        while (p != null){
            nodeCnt ++;
            p = p.next;
        }
        int cnt = nodeCnt / 2;

        // 反转 0-cnt 的节点
        Node pHead = new Node(-1);
        Node q = null;
        p = head;
        for(int i=0;i<cnt;i++){
            Node pNext = p.next;
            if(i == 0){
                pHead.val = p.val;
            }else {
                p.next = pHead;
                pHead = p;
            }
            q = pNext;
            p = pNext;
        }
        if(nodeCnt % 2 == 1){
            q = q.next;
        }

        // p,q同时遍历
        boolean flag = true;
        p = pHead;
        while (q != null){
            if(p.val != q.val){
                flag = false;
                break;
            }else {
                p = p.next;
                q = q.next;
            }
        }
        return flag;
    }


}
/*
4
1 2 2 1
true

5
1 2 3 2 1

5
1 2 3 2 3
 */