题解 | # 删除链表的倒数第n个节点#

删除链表的倒数第n个节点

http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

思路

#链表中倒数最后k个结点#,使用快慢指针。

快指针比慢指针先n步,快慢指针同步前进,快指针碰到null时,慢指针就是待删除结点,比起上一题,需要再维护一个pre结点,记录slow指针前面的结点,最后逻辑删除slow结点,返回head。

实现

import java.util.*;

public class Solution {
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        ListNode fast = head;
        ListNode slow = head;
        ListNode pre = null;
        int i = 0;
        for(i = 0; i < n & fast != null; i++) {
            fast = fast.next;
        }
        if(i < n && fast == null) return null;
        while(fast != null) {
            fast = fast.next;
            pre = slow;
            slow = slow.next;
        }
        if(pre == null) {
            return slow.next;
        }
        pre.next = slow.next;
        return head;
    }
}

因为题目保证n有效,比起#链表中倒数最后k个结点#可以删掉一些判断

import java.util.*;

public class Solution {
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        ListNode fast = head;
        ListNode slow = head;
        ListNode pre = null;
        for(int i = 0; i < n; i++) {
            fast = fast.next;
        }
        while(fast != null) {
            fast = fast.next;
            pre = slow;
            slow = slow.next;
        }
        if(pre == null) {
            return slow.next;
        }
        pre.next = slow.next;
        return head;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 10:56
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务