美文网首页
leetcode19. 删除链表的倒数第N个节点

leetcode19. 删除链表的倒数第N个节点

作者: 冰源 | 来源:发表于2018-09-21 23:00 被阅读7次
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:
---
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。

进阶:
你能尝试使用一趟扫描实现吗?
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        # h1在前,h2在后,h1与h2之间隔了n个距离;当h2到了末尾,h1就到了倒数n的位置
        h1=head
        h2=head
        while (n>0):
            h2=h2.next
            n-=1
        if h2 == None:
            return head.next
        h2 = h2.next
        while h2!=None:
            h1 = h1.next
            h2 = h2.next
        h1.next = h1.next.next
        return head



相关文章

网友评论

      本文标题:leetcode19. 删除链表的倒数第N个节点

      本文链接:https://www.haomeiwen.com/subject/blqtoftx.html