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

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

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

先让一个指针走n-1步,然后俩个指针一起走就找到了要删除的节点。

import java.util.*;

public class Solution {

    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        ListNode pre = head;
        ListNode bac = head;
        while((n-1)>0){
            bac = bac.next;
            n--;
        }
        ListNode prepre = null;
        while(null != bac.next){
            bac = bac.next;
            prepre = pre;
            pre = pre.next;
        }
        if(null == prepre){
            return head.next;
        }
        prepre.next = prepre.next.next;
        return head;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务