美文网首页
判断一个链表是否是回文结构

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

作者: shoulda | 来源:发表于2018-07-16 15:12 被阅读0次

    题目:给定一个链表的头节点head, 请判断该链表是否为回文结构。

    public static class Node {
            public int value;
            public Node next;
    
            public Node(int data) {
                this.value = data;
            }
        }
    
    public static boolean isPalindrome1(Node head) {
            Stack<Node> stack = new Stack<Node>();
            Node cur = head;
            while (cur != null) {
                stack.push(cur);
                cur = cur.next;
            }
            while (head != null) {
                if (head.value != stack.pop().value) {
                    return false;
                }
                head = head.next;
            }
            return true;
        }
    
    public static boolean isPalindrome2(Node head) {
            if (head == null || head.next == null) {
                return true;
            }
            Node right = head.next;
            Node cur = head;
            while (cur.next != null && cur.next.next != null) {
                right = right.next;
                cur = cur.next.next;
            }
            Stack<Node> stack = new Stack<Node>();
            while (right != null) {
                stack.push(right);
                right = right.next;
            }
            while (!stack.isEmpty()) {
                if (head.value != stack.pop().value) {
                    return false;
                }
                head = head.next;
            }
            return true;
        }
    

    相关文章

      网友评论

          本文标题:判断一个链表是否是回文结构

          本文链接:https://www.haomeiwen.com/subject/trrbpftx.html