LeetCode Medium: 19. Remove Nth Node From End of List

一、题目

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

Example:

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.

Note:

Given n will always be valid.

给定一个链接的 list,移除从尾到头数的第 n 个结点。

二、思路

快慢指针,让快指针距离慢指针 n 的距离,然后快慢指针一块移动,然后当快指针移动到头的时候,慢指针所指的位置就是要删除的那个。

三、代码

#coding:utf-8
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def removeNthFromEnd(head, n):
    """
    :type head: ListNode
    :type n: int
    :rtype: ListNode
    """
    dummy = ListNode(0)
    dummy.next = head
    start = end = dummy
    for i in range(n):
        start = start.next
    while start.next:
        start = start.next
        end = end.next
    end.next = end.next.next
    return dummy.next

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8881183.html