代码随想录算法训练营第四天 | 24. 两两交换链表中的节点&19.删除链表的倒数第N个节点&02.07. 链表相交&142.环形链表II

今日任务:

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

24. 两两交换链表中的节点 

题目链接:. - 力扣(LeetCode)

1. dymmy头结点

2. 画图理解整个交换过程

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyNode = new ListNode(-1, head);
        ListNode cur = dummyNode;
        ListNode temp;
        ListNode temp1;

        while(cur.next != null && cur.next.next != null) {
            temp = cur.next;
            cur.next = cur.next.next;
            temp1 = cur.next.next;
            cur.next.next = temp;
            temp.next = temp1;
            cur = temp;
        }

        return dummyNode.next;
    }
}


19.删除链表的倒数第N个节点 

题目链接:. - 力扣(LeetCode)

本质还是双指针,或者固定长度的窗口

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //双指针的方法,重要的一点,保留倒数N个节点的前一个节点
        ListNode dummy = new ListNode(-1, head);
        ListNode slowNode = dummy;
        int count = 0;
        ListNode cur = head;

        while(cur != null) {
            count++;
            if (count > n) {
                slowNode = slowNode.next;
            }
            cur = cur.next;
        }
        slowNode.next = slowNode.next.next;
        return dummy.next;
    }
}


02.07. 链表相交 

题目链接:. - 力扣(LeetCode)

最简单的方式是用hash数组。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> setA = new HashSet<>();
        ListNode curA = headA;
        while(curA != null) {
            setA.add(curA);
            curA = curA.next;
        }
        //判断是否相同
        ListNode curB = headB;
        while(curB != null) {
            if (setA.contains(curB)) {
                return curB;
            }
            curB = curB.next;
        }
        return null;
    }
}

142.环形链表II 

题目链接:. - 力扣(LeetCode)

除了使用快慢2个指针方法,最简单的方法还是hash表

public class Solution {
    public ListNode detectCycle(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        ListNode cur = head;
        while (cur != null) {
            if (set.contains(cur)) {
                return cur;
            }
            set.add(cur);
            cur = cur.next;
        }
        return null;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值