题目:
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.
链接: http://leetcode.com/problems/remove-nth-node-from-end-of-list/
一刷
Python
删除节点一般需要留指向被删除节点前一个节点。这类题目经常每换一步都要validate,比如开始查n==0,之后range(n-1)的循环里要检查fast == None,循环之后要检查是否可直接退出,第二个循环里检查fast.next,最后检查prev的指向内容。
这道题很简单,可是要按顺序在每一步找到合适的validate还是有些麻烦,最好是从一般到特殊来检查是否需要额外添加。测试例子1-->2-->3可以用n从1-4来测试。
# 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 """ if n == 0: return head fast = head for i in range(n-1): if fast != None: fast = fast.next else: return head else: if fast == None: return head prev = None slow = head while fast.next: fast = fast.next prev = slow slow = slow.next if prev: prev.next = slow.next return head else: return head.next
好思路:建立dummy节点,省略很多边界条件的检查,n>0时只移动fast,n<=0时同时移动fast, slow。
class Solution(object): def removeNthFromEnd(self, head, n): if n == 0: return head dummy = ListNode(0) dummy.next = head fast = dummy slow = dummy while fast.next: fast = fast.next if n <= 0: slow = slow.next n -= 1 slow.next = slow.next.next return dummy.next