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

2020-01-29  本文已影响0人  oneoverzero

题目描述:

给定一个链表,删除链表的倒数第 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

上一篇 下一篇

猜你喜欢

热点阅读