【LeetCode】19. Remove Nth Node From End of List 解题报告(Python)
标签(空格分隔): LeetCode
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/
题目地址:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
题目描述:
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?
题目大意
删除一个单链表的倒数第n个节点。
解题方法
这个题肯定是使用快慢指针啊,两个之间的距离是n,所以当快指针指向结尾的时候,慢指针正好指向了倒数第n个。因为要删除慢指针的位置,所以需要一个pre指针记录一下前面的那个节点的位置。就酱。
# 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
"""
root = ListNode(0)
root.next = head
fast, slow, pre = root, root, root
while n - 1:
fast = fast.next
n -= 1
while fast.next:
fast = fast.next
pre = slow
slow = slow.next
pre.next = slow.next
return root.next
日期
2018 年 6 月 23 日 ———— 美好的周末要从刷题开始