代码随想录二刷day04

本文介绍了力扣网站上的四个链表相关问题:交换链表节点、删除倒数第N个节点、链表相交以及环形链表II的解决方案,涉及迭代、递归等技巧。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言


一、力扣24. 两两交换链表中的节点

迭代

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode node = new ListNode(-1, head);
        ListNode prev = node, cur = head;
        int temp;
        while(cur != null && cur.next != null){
            temp = cur.val;
            cur.val = cur.next.val;
            cur.next.val = temp;
            prev = cur.next;
            cur = prev.next;
        }
        return node.next;
    }
}

递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        int temp;
        ListNode cur = head;
        temp = cur.val;
        cur.val = cur.next.val;
        cur.next.val = temp;
        ListNode node = swapPairs(cur.next.next);
        if(node == null){
            return cur;
        }
        return cur;
    }
}

二、力扣19. 删除链表的倒数第 N 个结点

直观法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null){
            return head;
        }
        ListNode node = new ListNode(-1, head);
        ListNode pre = node, p = head;
        int i = 0, size = 0;
        while(p != null){
            size ++;
            p = p.next;
        }
        if(n > size){
            return head;
        }
        p = head;
        while(i < size-n){
            i ++;
            pre = p;
            p = p.next;
        }
        pre.next = p.next;
        return node.next;
    }
}

双指针法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode node = new ListNode(-1, head);
        ListNode fast = node, slow = node;
        int i = 1;
        while(i <= n+1 && fast != null){
            i ++;
            fast = fast.next;
        }
        if(fast == null && i < n+1){
            return node.next;
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return node.next;
    }
}

三、力扣面试题 02.07. 链表相交

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode longL = new ListNode(-1, headA);
        ListNode shortL = new ListNode(-1, headB);
        ListNode pa = headA, pb = headB;
        int lenA = 0, lenB = 0, diff = 0;
        while(pa != null){
            lenA ++;
            pa = pa.next;
        }
        while(pb != null){
            lenB ++;
            pb = pb.next;
        }
        if(lenA > lenB){
            diff = lenA - lenB;
            longL.next = headA;
            shortL.next = headB;
        }else{
            diff = lenB - lenA;
            longL.next = headB;
            shortL.next = headA;
        }
        pa = longL.next; pb = shortL.next;
        for(int i = 0; i < diff; i++){
            pa = pa.next;
        }
        while(pa != null && pb != null){
            if(pa == pb){
                return pa;
            }
            pa = pa.next;
            pb = pb.next;
        }
        return null;
    }
}

四、力扣142. 环形链表 II

因为快指针的速度是慢指针的两倍, 所以,在进入环形之后, 在快慢指针相遇之前, 慢指针必然走不满一圈,设入环之前的节点数为x, 入环后到相遇节点之前为y个, 相遇节点到入环处为z个, 相遇时, 快指针走过的节点数是慢指针的2倍, 故有,2(x + y) = x + n(z + y) + y,, 化简后为, x = n(z +y)-y, 右边提取一个 y 得到,x = (n-1)(z+y) + z, 此时的慢指针,一定会先走完z, 然后就是n-1圈, 就一直在进入点等待x

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fastNode = head, slowNode = head;
        while(fastNode != null && fastNode.next != null){
            fastNode = fastNode.next.next;
            slowNode = slowNode.next;
            if(fastNode == slowNode){
                ListNode index1 = head;
                ListNode index2 = slowNode;
                while(index1 != index2){
                    index1 = index1.next;
                    index2 = index2.next;
                }
                return index1;
            }
        }
        return null;
    }
}
### 关于代码随想录 Day04 的学习资料与解析 #### 一、Day04 主要内容概述 代码随想录 Day04 的主要内容围绕 **叉树的遍历** 展开,包括前序、中序和后序三种遍历方式。这些遍历可以通过递归实现,也可以通过栈的方式进行迭代实现[^1]。 #### 叉树的遍历方法详解 ##### 1. 前序遍历(Pre-order Traversal) 前序遍历遵循访问顺序:根节点 -> 左子树 -> 右子树。以下是基于递归的实现: ```python def preorderTraversal(root): result = [] def traversal(node): if not node: return result.append(node.val) # 访问根节点 traversal(node.left) # 遍历左子树 traversal(node.right) # 遍历右子树 traversal(root) return result ``` 对于迭代版本,则可以利用显式的栈来模拟递归过程: ```python def preorderTraversal_iterative(root): stack, result = [], [] current = root while stack or current: while current: result.append(current.val) # 访问当前节点 stack.append(current) # 将当前节点压入栈 current = current.left # 转向左子树 current = stack.pop() # 弹出栈顶元素 current = current.right # 转向右子树 return result ``` ##### 2. 中序遍历(In-order Traversal) 中序遍历遵循访问顺序:左子树 -> 根节点 -> 右子树。递归实现如下: ```python def inorderTraversal(root): result = [] def traversal(node): if not node: return traversal(node.left) # 遍历左子树 result.append(node.val) # 访问根节点 traversal(node.right) # 遍历右子树 traversal(root) return result ``` 迭代版本同样依赖栈结构: ```python def inorderTraversal_iterative(root): stack, result = [], [] current = root while stack or current: while current: stack.append(current) # 当前节点压入栈 current = current.left # 转向左子树 current = stack.pop() # 弹出栈顶元素 result.append(current.val) # 访问当前节点 current = current.right # 转向右子树 return result ``` ##### 3. 后序遍历(Post-order Traversal) 后序遍历遵循访问顺序:左子树 -> 右子树 -> 根节点。递归实现较为直观: ```python def postorderTraversal(root): result = [] def traversal(node): if not node: return traversal(node.left) # 遍历左子树 traversal(node.right) # 遍历右子树 result.append(node.val) # 访问根节点 traversal(root) return result ``` 而迭代版本则稍复杂一些,通常采用双栈法或标记法完成: ```python def postorderTraversal_iterative(root): if not root: return [] stack, result = [root], [] while stack: current = stack.pop() result.insert(0, current.val) # 插入到结果列表头部 if current.left: stack.append(current.left) # 先压左子树 if current.right: stack.append(current.right) # 再压右子树 return result ``` #### 三、补充知识点 除了上述基本的叉树遍历外,Day04 还可能涉及其他相关内容,例如卡特兰数的应用场景以及组合问题的基础模板[^2][^4]。如果遇到具体题目,可以根据实际需求调用相应算法工具。 --- ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

乱世在摸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值