链表OJ题(中)

✅每日一练:链表的回文结构_牛客题霸_牛客网 (nowcoder.com)

 

    解题思路: 

回文分为两种情况,一种是奇数节点的链表,一种是偶数节点的链表,大致思路是先找到链表的中间节点,再让中间节点以后的节点指向反转,再定义左右指针,相向而行,判断链表是否回文,如图:

public class PalindromeList {
    public boolean chkPalindrome(ListNode head) {
        if(head == null){
            return false;
        }
        if(head.next == null){
            return true;
        }
        //找到中间节点
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        //把中间节点后面的节点指向反转
        ListNode cur = slow.next;
        while(cur != null){
            ListNode curNext = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curNext;
        }
        //让左右指针判断是否回文
        while(head != slow){
            if(head.val != slow.val){
                return false;
            }
            //判断链表偶数个节点的情况
            if(head.next == slow){
                return true;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;
    }
}

✅每日一练:141. 环形链表 - 力扣(LeetCode)


解题思路:

  定义快慢指针,让fast走2步,slow走1步,判断是否成环

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

✅每日一练:160. 相交链表 - 力扣(LeetCode)


 

解题思路:

    我们要确保两个链表同时在终点相遇,可以让长的链表先走两个链表的长度差,然后让长短链表同时走,走到终点时,判断二者尾结点的指向是否指向同一个地址,如果相等,那么肯定有相交点了:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        //求链表的长度,让长的的先走长度差的绝对值数
        int lenA = 0 ;
        int lenB = 0;
        ListNode pl = headA;
        ListNode ps = headB;
        while(pl != null){
            lenA++;
            pl = pl.next;
        }
        while(ps != null){
            lenB++;
            ps = ps.next;
        }
        pl = headA;
        ps = headB;

        //链表的长度差
        int len = lenA - lenB;

        //确保len始终大于0,pl指向长的链表,ps指向短的链表
        if(len < 0){
            pl = headB;
            ps = headA;
            len = lenB - lenA;
        }

        //让长的链表先走len步
        while(len-- != 0){
            pl = pl.next;
        }
        while(pl != ps){
            pl = pl.next;
            ps = ps.next;
        }
       return ps;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bc_小徐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值