Letcode Problem 19.Remove Nth Node From End of List answer.

Asked 1 years ago, Updated 1 years ago, 375 views

I have a question about Python's substitution rules regarding the answers shown below.
https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/1164537/short-simple-one-pass-solution-w-explanation-beats-100-no-dummy-node-required/?orderBy=most_votes

Some of the solutions include:

def removeNthFromEnd(self,head:ListNode,n:int) ->ListNode:
ptr, length = head, 0
while ptr:
    ptr, length = ptr.next, length+1
if length == n —return head.next
ptr=head
for i in range (1, length-n):
    ptr = ptr.next
ptr.next = ptr.next.next
return head

I understand the solution, but I don't understand why the contents of the head are changed in the code below.Python substitution is different from copy, so even if the ptr change is reflected in the head, I don't think the ptr is "the linear list starting with length-nth".

 ptr=head
for i in range (1, length-n):
    ptr = ptr.next
ptr.next = ptr.next.next

I would appreciate it if someone could tell me why the code above gives me the right answer.

python

2023-01-09 23:29

1 Answers

head may be mistaken for data representing the entire linear list

As you can see from reading the assumptions in the problem statement, ListNode refers to one element of a linear list.

#Definition for single-linked list.
# Class ListNode:
#     def__init__(self,val=0,next=None):
#         self.val = val
#         self.next = next

head points to its leading element, and for convenience it represents the entire linear list.Therefore, it returns head as the return value of the function.
(The exception is head.next returned only in the case where n==length is to remove the leading element.)

Therefore,

Finally, ptr is "a linear list starting with length-nth" and not "a linear list skipping the nth from the back of the original linear list."

The understanding that is correct, but I only use it within functions, so I think it is wrong to view it as a result of processing.

# To make it the nth one after the original linear list, the process is done at the point where the question is extracted.


2023-01-09 23:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.