Update remove_kth_node.py

This commit is contained in:
marina 2023-08-07 16:17:11 -07:00 committed by GitHub
parent d8d1887a85
commit 0389271f6b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,24 +8,23 @@ def remove_kth_node(self, head, n):
if head is None or head.next is None: if head is None or head.next is None:
return None return None
node = head # find the length of the list
lenght = 0 node, length = head, 0
# find the lenght of the list
while node: while node:
node = node.next node = node.next
lenght += 1 length += 1
if n == lenght: # if n is the entire list, remove head
if n == length:
return head.next return head.next
i = 0 # loop to kth element
node = head node, i = head, 0
while i < lenght - n - 1: while i <= length - n:
node = node.next node = node.next
i += 1 i += 1
# remove the kth element
node.next = node.next.next node.next = node.next.next
return head return head