通过快慢指针,找到倒数第N-1个元素
通过定义快慢指针,快指针先行N步,慢指针和快指针一起前进,快指针到达链表的尾部时,慢指针指向倒数第N-1个元素
定义数据结构
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
头指针解决删除第一个元素的问题
def removeNth(self, head, n):
tmp = ListNode(0)
tmp.next = head
fast = tmp
slow = tmp
快指针先行N步
while c < n:
fast = fast.next
c++
快慢指针一起走
while fast.next != None:
fast = fast.next
slow = slow.next
完整代码实现
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def removeNth(self, head, n):
tmp = ListNode(0)
tmp.next = head
fast = tmp
slow = tmp
c = 0
while c < n:
fast = fast.next
c++
while fast.next != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return tmp.next
|