判断链表是否回文结构

思路:
首先需要找到链表的中心节点,然后将中心节点后的链表进行反转,从链表两端进行遍历,判断链表是否是回文结构

public boolean chkPalindrome(){
        if(head==null){
            return false;
        }
        if(head.next==null){
            return true;
        }
        ListNode fast = this.head;
        ListNode slow = this.head;

        while (fast != null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //反转
        ListNode p = slow.next;
        while (p != null) {
            ListNode pNext = p.next;
            p.next=slow;
            slow=p;
            p=pNext;
        }
        while(slow!=this.head){
            if(slow.data!=head.data){
                return false;
            }
            if(this.head.next==slow){
                return true;
            }

            slow=slow.next;
            head=head.next;
        }
        return true;

        //slow往前    head 往后  .data不一样 返回false
        //直到相遇

    }
发布了67 篇原创文章 · 获赞 12 · 访问量 1519

猜你喜欢

转载自blog.csdn.net/qq_42174669/article/details/102874680