18 leetcode - Remove Nth Node From End of List

来源:互联网 发布:汉字笔画笔顺软件 编辑:程序博客网 时间:2024/06/05 11:34

指针追赶。
设两个指针,一个先走n步,然后同时走。

#!/usr/bin/python# -*- coding: utf-8 -*-'''英文:Given a linked list, remove the nth node from the end of list and return its head.中文:移除倒数第n个节点举例: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.'''# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def removeNthFromEnd(self, head, n):        """        :type head: ListNode        :type n: int        :rtype: ListNode        """        first = head        second = head        while n:            first = first.next            n -= 1            if first == None:#已经到了结尾了                if n > 0:    #说明n已经超过了链表的长度,直接返回头节点即可                    return head                else:#恰好删除头节点                    return head.next         #删除的节点在链表中间        while first.next:            first = first.next            second = second.next        #second.next为倒数第n个节点,让second.next = second.next.next就跳过了倒数第n个节点        second.next = second.next.next        return head
0 0