代码随想录算法训练营第4天| LeetCode 24. 两两交换链表中的节点 19.删除链表的倒数第N个节点

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 dummyhead = new ListNode(-1);
        dummyhead.next = head;
        ListNode cur = dummyhead;

        //保证接下来两个节点不为空
        while(cur.next != null && cur.next.next != null){
            //保存两个临时节点
            ListNode tmp1 = cur.next;
            ListNode tmp2 = cur.next.next.next;
            //开始改变方向
            cur.next = cur.next.next;
            cur.next.next = tmp1;
            cur.next.next.next = tmp2;

            //再移动两个节点
            cur = cur.next.next;
        }
        return dummyhead.next;
    }
}
19. 删除链表的倒数第 N 个结点

 关键是能想到第一个指针走n+1步

/**
 * 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 dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;
        //fast提前走n步
        while(n -- > 0 && fast != null){
            fast = fast.next;
        }
        //多走一步,保证slow指向删除节点的上一个节点
        fast = fast.next;
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值