19. Remove Nth Node From End of List(python)

来源:互联网 发布:取色笔 淘宝 编辑:程序博客网 时间:2024/04/28 17:11

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.
runtime:56ms
总结:
创建一个头结点
快慢指针法,快指针比慢指针多走n步,快指针指向最后一个元素时,慢指针指向删除元素的前一个元素

class ListNode(object):     def __init__(self, x):            self.val = x            self.next = Noneclass Solution(object):    def removeNthFromEnd(self, head, n):        if not head:            return None        p=ListNode(0)        p.next=head        slow=p        fast=p        for i in range(n):            fast=fast.next        while fast.next:            fast=fast.next            slow=slow.next        slow.next=slow.next.next        return  p.next
0 0