题解 | #删除链表的倒数第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
        ListNode fast = head, slow = head;
        // 1→2→3→4→5
        for(int i = 0 ; i < n; i++){
            fast = fast.next;
        }
        //     ↓
        // 1→2→3→4→5
        // ↑

        if(fast == null){ return head.next;}
        while(fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }
        //     ↓ ↓ ↓
        // 1→2→3→4→5
        // ↑ ↑ ↑

        slow.next = slow.next.next;
        return head;

    }
}
全部评论

相关推荐

notbeentak...:真的nc,算毕业6月份,要给这种b公司打半年多白工😅
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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