当前位置:网站首页>LeetCode#19. Delete the penultimate node of the linked list

LeetCode#19. Delete the penultimate node of the linked list

2022-07-06 15:21:00 Rufeng ZHHH

For this problem, we can first get the sum of the number of nodes in the linked list ( Here I use count To express ), Then judge when the special situation ( Request to delete the first node ) And normal operation , Then carry out the corresponding steps .

# 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:
        count=0
        pre=head
        cur=head
        while pre != None:
            count+=1
            pre=pre.next # Get the length count
        if count-n==0:
            return head.next
        for i in range(count-n-1):
            cur=cur.next
        cur.next=cur.next.next
        return head

 

原网站

版权声明
本文为[Rufeng ZHHH]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131319092422.html