每日一题--LeetCode 234(回文链表)java

题目描述:

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

进阶:
你能否用 O(n) 时间复杂度和 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;
        }
        int len=0;
        ListNode cur=null,tmp=head;
        ListNode fast=head,slow=head;
        //使用快慢指针将练链表划分成两段
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        //将链表后半段逆置
        while(slow!=null){
            ListNode newNode=new ListNode(slow.val);
            if(cur==null){
                cur=newNode;
            }else{
                newNode.next=cur;
                cur=newNode;
            }
            slow=slow.next;
        }
        //进行比较判断
        while(cur!=null){
            if(cur.val!=head.val){
                return false;
            }
            cur=cur.next;
            head=head.next;
        }
        return true;
    }
}

解题思路二:也是使用快慢指针的方法,只不过直接将链表在原有基础上逆置,空间复杂度为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||head.next==null){
            return true;
        }
        //注意点,这里fast的赋值
        ListNode fast=head.next,slow=head;
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode tmp=slow.next;
        ListNode newhead=null;
        slow.next=null;
        //逆置后半段链表
        while(tmp!=null){
            ListNode cur=tmp.next;
            tmp.next=newhead;
            newhead=tmp;
            tmp=cur;
        }
        //将两段链表进行比较
        while(newhead!=null){
            if(newhead.val!=head.val){
                return false;
            }
            newhead=newhead.next;
            head=head.next;
        }
        return true;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值