• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

判断一个链表是否为回文结构

开发技术 开发技术 6小时前 5次浏览

链接

给定一个链表,请判断该链表是否为回文结构。

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));
        }
    }
}

程序员灯塔
转载请注明原文链接:判断一个链表是否为回文结构
喜欢 (0)