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

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

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


/*
 * 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 || n < 1) {
            return head;
        }
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        
        if (len < n) {
            return head;
        } else if (len == n) {
            return head.next;
        }
        
        ListNode pre = head;
        cur = pre;
        int i = 0;
        ListNode next = null;
        while (i < len - n) {
            next = cur.next;
            pre = cur;
            cur = next;
            i++;
        }
        
        pre.next = cur.next;
        cur.next = null;
        return head;
    }
    
    
    
    
    
}
全部评论

相关推荐

05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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