Remove Nth Node From End of List 的

来源:互联网 发布:网络电影市场规模 编辑:程序博客网 时间:2024/05/22 09:48

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点

一.目标:如上

二.思路:使用两个节点,让一个节点领先n+2,当开头的节点走到null 时,后一个节点走到了要删除的节点的前节点,此时可进行删除。

三.易错点:分不清到底领先多少步和判断 n 与链表的长度的关系

代码如下:

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(n < 0){
            return null;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode preDelete = dummy;
        
        for(int i = 0; i < n; i++){
            if(head == null){
                return null;    //必须 因为也许给的数值不符合链表情况
            }
            head = head.next;
        }
        
        while(head != null){
            head = head.next;
            preDelete = preDelete.next;
        }
        preDelete.next = preDelete.next.next;
        
        return dummy.next;
    }
}




0 0