删除链表倒数第k个节点
Last updated
Last updated
{1,2},2 {2}class Solution:
def removeNthFromEnd(self , head , n ):
# write code here
# input: head of list , n: the last n node
# idea:
# 1. find the length of linkedlist
# 2. find the position of the last n node
#
#
#
#
if not head or not n:
return head
# find the position of the last n node
cnt = 0
cur = fake_head = ListNode(None)
fake_head.next = head
while cur:
cur = cur.next
cnt += 1
pos = cnt - n
if pos <0:
return head
# find the n node
cnt = 0
cur = fake_head
while cur:
if cnt == pos -1 and cur.next:
cur.next = cur.next.next
break
cur = cur.next
cnt += 1
return fake_head.next