LeetCode 19. Remove Nth Node From End of List 20170417

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

For 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.
Try to do this in one pass.

 题目大意:给定一个单链表和一个整数n,删除链表倒数第n个节点并且返回头结点。最好只遍历一次。

解题思路:一开始的想法是遍历一遍链表,得到链表的长度,然后用长度减去n,找到该节点。但是发现这样做复杂度为O(2n),不能做到遍历一次。随后想到用快慢指针的方法,在遍历链表的同时用另一个指针一直指向当前节点的前n个节点,当当前链表遍历完后,就能找到需要删除的节点。如果直接正常从head节点开始构造链表,万一需要删除的节点为head节点会比较难处理,因此在head节点前面再放一个节点beforehead。还有一个需要注意的是需要删除的节点是slow.next而不是slow节点。

# Definition for singly-linked list.
  # class ListNode(object):
  # def __init__(self, x):
  # self.val = x
  # self.next = None

  class Solution(object):
    def removeNthFromEnd(self, head, n):
    """
    :type head: ListNode
    :type n: int
    :rtype: ListNode
    """
    beforehead=ListNode(0)
    beforehead.next=head
    fast=beforehead
    slow=beforehead
    while n>0:
      fast=fast.next
      n-=1
    while fast.next:
      fast=fast.next
      slow=slow.next
    slow.next=slow.next.next
    return beforehead.next

原文地址:https://www.cnblogs.com/fangdai/p/6722764.html