Given a linked list, remove the nth node from the end of list and return its head. Given n will always be valid and try to do this in one pass.
For example,
1 2 3
| 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.
|
思路
这是一道非常典型的快慢指针题。双指针的操作在链表中比较常用,这样的操作可以省去频繁对链表进行遍历的开销,非常方便。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ fast = head headflag = 1 for i in range(n): fast = fast.next if (fast): fast = fast.next headflag = 0 slow = head while(fast): fast = fast.next slow = slow.next if (slow == head): if (headflag): head = slow.next else: slow.next = slow.next.next else: slow.next = slow.next.next return head
|