Remove Nth Node From End of List从尾部开始删除第N个节点

[抄题]:

Given a linked list, remove the nth node from the end of list and return its head.

Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

[思维问题]:

[一句话思路]:

快指针走n步,慢指针再走,形成线段差

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. dummy,corner case已经成为标配了
  2. preDelete要从最前开始指,指向dummy
  3. 只需要写head.next != null,因为一次只走一步

[总结]:

  1. 只需要写head.next != null,因为一次只走一步

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构,为什么不用别的数据结构]:

[其他解法]:

[Follow Up]:

[题目变变变]:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        if (n <= 0) {
            return head;
        }
        for(int i = 0; i < n; i++) {
            head = head.next;
        }
        
        ListNode preDelete = dummy;
        while(head != null) {
            head = head.next;
            preDelete = preDelete.next;
        }
        preDelete.next = preDelete.next.next;
        
        return dummy.next;
    }
}
View Code

 

posted @ 2017-12-27 22:46  苗妙苗  阅读(182)  评论(0编辑  收藏  举报