链表回文

链表回文

Description

判断一个单向链表是否为回文结构。自定义链表数据结构,要求时间复杂度为O(n),额外空间复杂度为O(1)。

Input

输入第一行为用例个数, 每个测试用例输入的每一行的值用空格隔开,第一个值为节点个数,后面为每一个节点值

Output

是回文则输出true,不是则输出false,一行表示一个链表的结果。

Solution

public class ListPalindrome {

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int caseNum = in.nextInt();
        for(int i = 0; i < caseNum; i++){
            int nodeNum = in.nextInt();
            Node head = new Node(in.next());
            Node pre = head;
            for(int j = 1; j < nodeNum; j++){
                Node node = new Node(in.next());
                pre.next = node;
                pre = node;
            }
            System.out.println(isPalindrome(head));
        }
    }

    public static boolean isPalindrome(Node head){
        if(head == null || head.next == null){
            return true;
        }
        if(head.next.next == null){
            return head.val.equals(head.next.val);
        }

        Node fast = head.next.next;
        Node slow = head.next;
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }

        Node pre = null;
        Node next = null;
        while(slow != null){
            next = slow.next;
            slow.next = pre;
            pre = slow;
            slow = next;
        }
        Node tail = pre;

        while(head != null){
            if(!head.val.equals(tail.val)){
                return false;
            }
            head = head.next;
            tail = tail.next;
        }
        return true;
    }

    static class Node{
        String val;
        Node next;

        Node(String val){
            this.val = val;
        }
    }
}

你可能感兴趣的:(链表回文)