leetcode--19. Remove Nth Node From End of List

来源:互联网 发布:linux进程间通讯机制 编辑:程序博客网 时间:2024/05/16 11:43

题目:19. Remove Nth Node From End of List

链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

大概意思是要删除单链表的倒数第N个结点,要求只能遍历一遍。那就先设置一个指针从前往后遍历到第N个结点,然后再设置一个指针从头开始同步遍历,第一个指针遍历到链尾的时候第二个指针的位置不就刚刚好嘛。

python:

# 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        """        if not head.next:            return []        temp=res=head        pre=ListNode(0)        index=1        while head:            if index>n:                pre=temp                temp=temp.next            head=head.next            index+=1        if n==index-1:            return res.next        pre.next=pre.next.next        return res


原创粉丝点击