leetcode解题之回文链表

本文介绍了一种算法,用于判断链表是否为回文结构。首先通过一个简单的方法,利用额外空间进行对比,然后提出了一个更高效的解决方案,使用O(1)的空间复杂度,通过快慢指针找到链表的中点,并反转后半部分链表进行对比。

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true

进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

先写一个简单的迭代法对比法(使用额外空间)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode temNode = head;
        String s1="",s2="";
        while(temNode!=null){
            s1+=temNode.val;
            s2=temNode.val+s2;
            temNode=temNode.next;
        }
        return s1.equals(s2);
    }
}

如果使用空间复杂度为O(1),基本上要找到中间值,但是对于链表不会啊,想不到还是看官方题解吧,使用快慢指针,慢指针一次走一位,快指针一次走两位,当快指针走到末尾时,慢指针正好走到中间位置。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
       if(head==null) return  true;
       ListNode firstOfEndHalf=firstOfHalfNode(head);
       ListNode reserverList = reserverListNode(firstOfEndHalf);
       while(reserverList!=null){
           if(reserverList.val!=head.val) return false;
           reserverList=reserverList.next;
           head=head.next;
       }
       return true;
    }
    //获取后半部分的第一个节点
    public ListNode firstOfHalfNode(ListNode head){
        ListNode fast=head;
        ListNode slow=head;
        while(fast.next!=null&&fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow.next;
    }
    //反转链表
    public ListNode reserverListNode(ListNode head){
        ListNode prev=null;
        ListNode cure=head;
        while(cure!=null){
            ListNode temNode = cure.next;
            cure.next=prev;
            prev=cure;
            cure=temNode;
        }
        return prev;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值