这题主要是链表长度未知,所以需要先遍历一遍链表。或许有其他更好的方法,但我目前没想到。今天看到一个学弟写的前端三维代码,狠狠的破防了,我还是太菜了,最近也在学前端的一些东西,但目前还是个菜鸡。最近有个想法就是自己开发一个GIS应用程序,也是采用python,看看吧,能做出来我会发布的,不要有太多希望!
方法一
# -*- coding: utf-8 -*-
"""
@Time : 2022/8/14 15:34
@Author : FJC
@File : 删除链表道术第N个节点.py
@Software: win10 python3.7
"""
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
class Solution:
def removeNthFromEnd(self,head,n):
dummy_head=ListNode(0)
dummy_head.next=head
cur=dummy_head
pre=cur
count=0
while cur.next!=None:
cur=cur.next
count+=1
while pre.next!=None:
if count==n:
pre.next=pre.next.next
break
else:
pre=pre.next
count-=1
return dummy_head.next
方法二
第二个方法是比较主流的,其原理就是定义快慢指针fast和slow,则fast-slow=n,即fast和slow之间始终保持n的距离,当fast离开列表后,slow刚好在要删除位置的前一个节点。
# -*- coding: utf-8 -*-
"""
@Time : 2022/8/14 16:49
@Author : FJC
@File : 6_删除链表倒数第N个节点_自测.py
@Software: win10 python3.7
"""
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
class Solution:
def removeNthFromEnd(self,head,n):
dummy_head=ListNode(0)
dummy_head.next=head
fast=dummy_head
slow=fast
for _ in range(n):
fast=fast.next
while fast.next==None:
slow=slow.next
fast=fast.next
slow.next=slow.next.next
return dummy_head.next