题解 | #删除链表的倒数第n个节点#注意删除头部的情况

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

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        if(head == null || head.next == null){
            return null;
        }
        //第一步 计算链表的长度
        int length = 0;
        ListNode ln = head;
        while(ln != null){
            length ++;
            ln = ln.next;
        }
        //第二步 找到倒数第n个节点的前一个节点
        int index = length - n;
        if(index == 0){
            //头部删除
            return head.next;
        }
        ListNode pre = head;
        for(int i =0;i<index-1;i++){
            pre = pre.next;
        }
        //第三步 删除 拼接
        pre.next = pre.next.next;
        return head;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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