当前位置 : 主页 > 手机开发 > ROM >

Lintcode174-Remove Nth Node From End of List-Easy

来源:互联网 收集:自由互联 发布时间:2021-06-10
174.Remove Nth Node From End of List Given a linked list, remove the nthnode from the end of list and return its head. Example Example 1:Input: list = 1-2-3-4-5-null, n = 2Output: 1-2-3-5-nullExample 2:Input: list = 5-4-3-2-1-null, n = 2O

174. Remove Nth Node From End of List

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

Example

Example 1:
	Input: list = 1->2->3->4->5->null, n = 2
	Output: 1->2->3->5->null


Example 2:
	Input:  list = 5->4->3->2->1->null, n = 2
	Output: 5->4->3->1->null

Challenge

Can you do it without getting the length of the linked list?

Notice

The minimum number of nodes in list is n.

 

双指针法:

定义快慢指针,先同时指向dummy结点。快指针(head)先比慢指针(preDelete)多走n步。

然后,快慢指针一起走,当快指针指向链表最后一个结点时,慢指针指向就是要删除结点的前一个结点。

ps: 对单向链表而言,删除结点时,必须操作要删除结点的前一个结点,而不是要删除的结点本身,否则无法使要删除结点的前一个和后一个结点连接。这也是这个题中,慢指针指向要删除结点的前一个结点,也因此推出快指针的临界位置。

代码:

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(-1);
    dummy.next = head;
    head = dummy;
    ListNode preDelete = dummy;
    
    for (int i = 1; i <= n; i++) {
        head = head.next;
    }
    while (head.next != null) {
        head = head.next;
        preDelete = preDelete.next;
    }
    preDelete.next = preDelete.next.next;
    return dummy.next;
}

考虑特殊情况(n <= 0, head == null)

public class Solution {
    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;
    }
}
网友评论