判断链表是否是回文结构

2019-02-27  本文已影响0人  霍运浩

1,解题思路

一个快指针 一个慢指针 快指针每次走两部,慢指针每次走一步,快指针走完链表,慢指针就走到了链表中间,然后将慢指针后面的节点装入栈中,然后重head开始 逐一对比。

public static boolean test(Node head){
        if(head==null || head.next==null){
            return false;
        }
        Node slow=head;
        Node fast=head;
        Stack<Integer> nodeStack=new Stack<Integer>();
        while(fast!=null){
            nodeStack.add(slow.data);
            slow=slow.next;
            fast=fast.next.next;
        }
        int size=0;
        while(head!=null){
            size++;
            head=head.next;
        }
        if(size/2==0){
            slow=slow.next;
        }
        while(slow!=null){
            if(nodeStack.pop()!=slow.data){
                return false;
            }
            slow=slow.next;
        }
        
        return true;    
    }
上一篇 下一篇

猜你喜欢

热点阅读