码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——回文链表

时间:2020-06-03 16:05:25      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:指针   判断   return   class   输入   leetcode   rom   vat   lin   

Q:请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true

A:
1.reverse以后对比。
因为这里是递归reverse,所以之前要先复制一个原链表。

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null)
            return true;
        ListNode node = head.next;
        ListNode head1 = new ListNode(head.val);
        ListNode temp = head1;
        while(node!=null){
            int val = node.val;
            temp.next = new ListNode(val);
            temp = temp.next;
            node = node.next;
        }
        ListNode head2 = reverse(head);
        ListNode node1 = head1;
        ListNode node2 = head2;
        while (node1 != null) {
            if (node1.val != node2.val)
                return false;
            node1 = node1.next;
            node2 = node2.next;
        }
        return true;
    }

    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode node = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }

2.双指针
主要是找到中点再reverse,我觉得这样就没什么意思了……

    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode node = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null)
            return true;
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {//找到中点,如果是偶数,为前一个点
            slow = slow.next;
            fast = fast.next.next;
        }
        fast = reverse(slow.next);
        slow.next = null;//cut前后两段
        slow = head;
        while(fast!=null){//这里一定要是fast的长度,fast是后半段,slow是前半段,若为奇数长度链表,slow更长
            if(slow.val!=fast.val)
                return false;
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }

LeetCode——回文链表

标签:指针   判断   return   class   输入   leetcode   rom   vat   lin   

原文地址:https://www.cnblogs.com/xym4869/p/13037603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!