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

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

作者: oneoverzero | 来源:发表于2020-01-29 17:06 被阅读0次

题目描述:

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

代码:

# 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
        """
        slow = fast = head
        for i in range(n):
            fast = fast.next
        if not fast: # 这个判断语句是为了处理一些边界情况
            return head.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head

思路分析:

用双指针:slowfast 。参见: https://www.cnblogs.com/yangyalong/p/9744829.html

相关文章

网友评论

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

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