接外包,有相关需求的可以联系我:Telegram | Email

删除链表的倒数第 N 个结点 | 双指针

该文章创建(更新)于02/21/2022,请注意文章的时效性!

描述

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

思路

双指针技巧,快慢指针。

Code

  • 提交Code
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        fast = head
        slow = head

        while(n >= 0):
            if(fast == None):
                head = head.next
                return head
            fast = fast.next
            n -= 1

        while( fast != None):
            fast = fast.next
            slow = slow.next

        slow.next = slow.next.next

        return head
  • 完整Code
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def removeNthFromEnd(self, head:ListNode,n:int):

        listN = ListNode(head[0])
        tmp = listN
        # 环状链表的构造
        for m in range(1,head.__len__()):
            listN.next = ListNode(head[m])
            listN = listN.next

        print('-----------------------')

        fast = tmp
        slow = tmp

        # if(n == 5):
        #     tmp = tmp.next
        #     return tmp

        while (n >= 0):
            # 用于判断是否为移除【正数】第一个数字的情况
            if(fast == None):
                tmp = tmp.next
                return tmp
            fast = fast.next
            n -= 1
        print('888888888888888888888888888888')

        while (fast != None):
            fast = fast.next
            slow = slow.next

        slow.next = slow.next.next
        print('888888888888888888888888888888')
        return tmp



head = [1,2]
S = Solution()
print("###################result###################")
result = S.removeNthFromEnd(head,1)
print("result"+str(result))
print('-------------------------------------------')
while result != None:
    print(result.val)
    result = result.next


👇 Share | 分享 👇


要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2022/02/21/remove-nth-node-from-end-of-list/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



微信公众号

👉 NewsLetter ❤️ 邮箱订阅 👈

优惠码


阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
域名 | namesiloemperinter(1美元)