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.
Follow up:
Could you do this in one pass?
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def removeNthFromEnd(self, head, n): 9 """ 10 :type head: ListNode 11 :type n: int 12 :rtype: ListNode 13 """ 14 dummy = ListNode(-1) 15 dummy.next = head 16 cur, slow = dummy, dummy 17 while n > 0: 18 cur = cur.next 19 n -= 1 20 while cur.next is not None: 21 slow = slow.next 22 cur = cur.next 23 slow.next = slow.next.next 24 return dummy.next 25
原文地址:https://www.cnblogs.com/xuanlu/p/11711312.html
时间: 2024-11-04 14:45:50