重生之从零开始刷代码随想录的生活--第5天/24两两交换链表中节点/19删除链表的倒数第N个节点/160链表相交/142环形链表Ⅱ

LeetCode-24,19,160,142:

24.两两交换链表中节点
19.删除链表的倒数第N个节点
160.链表相交
142.环形链表Ⅱ

第一题:
在这里插入图片描述

使用递归法

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode temp = head.next;
        ListNode newhead = swapPairs(temp.next);
        temp.next = head;
        head.next = newhead;
        return temp;
    }
}

在这里插入图片描述

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int length = 0;
        int count = 0;
        ListNode dummyhead = head;
        ListNode cur = new ListNode(0);
        cur.next = head;
        while(dummyhead!=null){
            dummyhead = dummyhead.next;
            length++;
        }
        int index = length-n;
        if(index==0){
            return head.next;
        }
        if(length==1){
            return null;
        }
        while(length>0){
            cur = cur.next;
            count++;
            if(count==index){
                if(cur.next!=null){
                    cur.next = cur.next.next;
                    break;
                }
            }
        }
        return head;
    }
}

在这里插入图片描述

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null || headB==null){
            return null;
        }
        ListNode cur1 = headA;
        ListNode cur2 = headB;
        while (cur1!=cur2){
            if(cur1 !=null){
                cur1 = cur1.next;
            }else{
                cur1 = headB;
            }
            if(cur2!=null){
                cur2 = cur2.next;
            }else{
                cur2=headA;
            }

        }
        return cur1;
    }
}

在这里插入图片描述

思考

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (true){
            if(fast == null || fast.next == null){
            	return null;
            }
            slow = slow.next;
            fast = fast.next.next;
            if(slow==fast){
                break;
            }
        }
        fast = head;
        while (slow!=fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值