代码随想录算法训练营第四天 | 24 两两交换链表中的节点 19 删除链表的倒数第 N 个节点 面试题 02.07 链表相交

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

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。
你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
输入:head = [1,2,3,4]
输出:[2,1,4,3]

自己想不明白去看了视频,看完视频之后的思路:
1.首先确定循环终止情况,
第一种链表元素个数为奇数时,需要判断cur.next.next为null终止循环。
第二种链表元素为偶数时,要判断cur.next为null时终止循环。
2.确定交换过程,有虚拟头结点真的方便了很多,不用对头结点单独分类写代码。
最重要的步骤应该是,保存cur.next 和 cur.next.next.next 防止后边改完之后节点丢失。

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0,head);
        ListNode cur = dummy;
        ListNode temp;
        ListNode temp1;
        while(cur.next != null && cur.next.next != null){
            temp = cur.next;
            temp1 = cur.next.next.next;
            cur.next = cur.next.next;
            cur.next.next = temp;
            temp.next = temp1;
            cur = cur.next.next;
        }
        return dummy.next;
    }
}

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

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0,head);
        ListNode fast = dummy;
        ListNode slow = dummy;
        for (int i = 0; i < n  ; i++){
        fast = fast.next;
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

LeetCode 面试题 02.07 链表相交

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;
        int LenA = 0 , LenB = 0;
        while(curA != null){
            LenA++;
            curA = curA.next;
        }
        while(curB != null){
            LenB++;
            curB = curB.next;
        }
        curA = headA;
        curB = headB;
        if(LenA < LenB){
            int LenT = LenA ;
            LenA = LenB;
            LenB = LenT;
            ListNode T = curA;
            curA = curB;
            curB = T;
        }
        int gap = LenA - LenB;
        for(int i = 0; i<gap ; i++){
            curA = curA.next;
        }
        while(curA != null){
            if(curA == curB){
                return curA;
            }
            curA = curA.next;
            curB =curB.next;
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值