判断一个链表是否为回文结构
给定一个链表,请判断该链表是否为回文结构。
import java.util.Scanner;
public class Main {
    static class Node {
        Node next;
        int val;
        public Node(int val) {
            this.val = val;
        }
    }
    private static Node findPreMid(Node head) {
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        Node slow = head.next;
        Node fast = head.next.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private static Node reverse(Node head) {
        if (head == null) {
            return null;
        }
        Node pre = null, cur = head, next;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    // 1->2<-3
    // 1->2<-3<-4
    private static boolean solve(Node head) {
        if (head == null || head.next == null) {
            return true;
        }
        Node mid = findPreMid(head);
        Node rightHead = reverse(mid);
        boolean res = true;
        Node cur1 = head, cur2 = rightHead;
        while (cur1 != null && cur2 != null) {
            if (cur1.val != cur2.val) {
                res = false;
                break;
            }
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        reverse(rightHead);
        return res;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            Node head = new Node(in.nextInt());
            Node pre = head;
            while (--n > 0) {
                Node node = new Node(in.nextInt());
                pre.next = node;
                pre = node;
            }
            System.out.println(solve(head));
        }
    }
}
    心之所向,素履以往 生如逆旅,一苇以航

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号