LeetCode234题:回文链表(Java)

题目描述:
在这里插入图片描述
解法1:
    先通过快慢指针,快指针走2步,慢指针走1步,找到链表中间结点。然后通过头插法翻转后半段链表。然后将前半段链表和后半段链表逐个比较,有不相同返回false,全部相同返回true。

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null) return true;
        ListNode fast = head, slow = head, pre = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            pre = slow;
            slow = slow.next;
        }
        pre.next = null;
        slow = fanzhuan(slow);
        fast = head;
        while(fast != null){
            if(fast.val != slow.val) return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    public ListNode fanzhuan(ListNode head){
        ListNode cur = new ListNode(-1);
        ListNode pre = null;
        while(head != null){
            cur.next = head;
            ListNode next = head;
            head = head.next;
            next.next = pre;
            pre = next;
        }
        return cur.next;
    }
}

在这里插入图片描述
解法2:
    首先遍历链表得到链表长度,创建一个和链表长度相同长度的数组。然后再次遍历链表,按次序将链表值写入数组中。在数组中通过首尾双指针的方法,首指针往后移,尾指针往前移,比较两个指针的值。如果有不相同,则返回false,全部相同,则返回true。

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null) return true;
        int count = 0;
        ListNode cur = head;
        while(head != null){
            count++;
            head = head.next;
        }
        int[] number = new int[count];
        count = 0;
        while(cur != null){
            number[count++] = cur.val;
            cur = cur.next;
        }
        int i = 0, j = number.length - 1;
        while(i <= j){
            if(number[i] != number[j]) return false;
            i++; j--;
        }
        return true;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值