Leetcode #19. Remove Nth Node From End of List 移除倒数第N个链表节点 解题小节

1 题目理解

我昨天又忘了更新了。。~~(>_<)~~ 先补

这道题就是说,删除链表的倒数第N个节点。。
链表本身是不知道有多少个元素的。。不过这种题都一个解法
设置Faster和slower两个指针,faster指针比slower先走k-1步。。然后再一起移动。。这样faster到头时,slower也指向了倒数第k个了~~~

然后就标准的移除了。。很简单。。不多说,取快递去了

2 原题

Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

Subscribe to see which companies asked this question

3 AC解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * 本质上,倒数第n个,只需要设置两个指针,一个走得快,一个走得慢
     * 走得快的比走的慢的多走n步就可以,当走的快的到了尾巴,那么也到了倒数第n个的位置了
     * 
     * 这题只需要注意初始的边界调节,比如只有一个且删除第一个怎么办,我是采用多创建了指针,指在头结点之前就好
     * */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode faster=head,slower;
        ListNode prehead=new ListNode(0);
        prehead.next=head;
        slower=prehead;
        //首先多走n步
        for(int i=0;i<n;i++){
            faster=faster.next;
        }
        while(faster!=null){
            faster=faster.next;
            slower=slower.next;
        }
        //删除slower
        slower.next=slower.next.next;
        return prehead.next;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值