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

给定一个链表的头节点head, 请判断该链表是否为回文结构。 例如: 1->2->1, 返回true。 1->2->2->1, 返回true。
15->6->15, 返回true。 1->2->3, 返回false。
进阶: 如果链表长度为N, 时间复杂度达到O(N), 额外空间复杂度达到O(1)。

解法一:

使用快慢指针将slow指向的链表的一半压入进栈中,然后slow继续向后走,同时栈中弹出元素,对比

对于奇数个链表 1->2->3->2->1 slow指向3

对于偶数个链表 1->2->2->1 slow指向第一个2

需要的空间复杂度为O(N/2)

 

public static boolean isPalindrome1(Node node){
        if(node == null || node.next == null) return true;
        Node fast = node;
        Node slow = node;
        Stack<Node> stack = new Stack<>();
        boolean flag = true;
        while(fast.next != null && fast.next.next != null){
            stack.push(slow);
            fast = fast.next.next;
            slow = slow.next;
        }
        slow = slow.next;
        if(stack.peek().val != slow.val){
            slow = slow.next;
        }
        while(!stack.empty() && slow != null){
            if(stack.pop().val != slow.val){
                flag = false;
                break;
            }
            slow = slow.next;
        }
        if(flag && stack.empty() && slow == null){
            return true;
        }else{
            return false;
        }
    }

 

  

解法二:

使用快慢指针,找到链表的中点,将中点右边的链表均反转,然后两头重新遍历,

对比,若有不同的则返回false,否则返回true

注意在返回之前,要将链表重新整理回原来的顺序

1->2->3->2->1  变为 1->2->3<-2<-1 

 

posted @ 2018-04-08 22:19  SkyeAngel  阅读(2428)  评论(0编辑  收藏  举报