判断单链表是否是回文结构的3种方法

10 篇文章 0 订阅
4 篇文章 0 订阅
  • 问题描述
    判断单链表是否是回文结构。

  • 解决方案1
    将链表中的数据全部压入堆栈,然后再依次弹出和原来的链表进行对比。

  /**
     * 全部压栈,然后依次弹出对比
     * @param head
     * @return
     */
    public static boolean isPalindrome1(Node head){
        Node cur = head;
        Stack<Integer> stack = new Stack<>();
        while(cur != null){
            stack.push(cur.value);
            cur = cur.next;
        }
        cur = head;
        while(cur != null){
            if(cur.value != stack.pop())
                return false;
            cur = cur.next;
        }
        return true;
    }

  • 解决方案2
    首先利用快慢指针找到链表的中间位置,将后半部分压栈,然后再依次弹出和原来的链表进行对比。
   /**
     * 后半部分压栈,然后依次弹出对比
     * @param head
     * @return
     */
    public static boolean isPalindrome2(Node head){
        //首先利用快慢指针找链表中点
        Node slow = head;
        Node fast = head;

        while(fast.next != null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        Node cur = slow.next;
        Stack<Integer> stack = new Stack<>();
        while(cur != null){
            stack.push(cur.value);
            cur = cur.next;
        }
        cur = head;
        while(!stack.isEmpty()){
            if(stack.pop() != cur.value)
                return false;
            cur = cur.next;
        }
        return true;
    }

  • 解决方案3
    首先利用快慢指针找到链表的中间位置,然后将链表后半部分逆序,最后将链表的后半部分和前半部分依次对比,看是否一样。
 /**
     * 前半部分压栈,后半部分逆序,然后对比
     * @param head
     * @return
     */
    public static boolean isPalindrome3(Node head){
        //首先利用快慢指针找链表中点
        Node slow = head;
        Node fast = head;

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

        cur = invertLinkedList(cur);
        while(cur != null){
            if(cur.value != head.value)
                return false;
            cur = cur.next;
            head = head.next;
        }
        return true;
    }

    //逆序单链表
    public static Node invertLinkedList(Node head){
        Node res;
        if(head == null)
            return null;
        res = head;
        Node cur = head.next;
        head.next = null;//链表结尾置为空
        while(cur != null){
            Node temp = cur;
            cur = cur.next;
            temp.next = res;
            res = temp;
        }
        return res;
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值