[leetcode]Remove Nth Node From End of List
简单题。唯一的小技巧是使用了指向指针的指针。
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	ListNode * forward = head;
		ListNode ** current = &head;
        n--;
		while (n--)
		{
			forward = forward->next;
		}
		while (forward->next != 0)
		{
			forward = forward->next;
			current = &((*current)->next);
		}
		*current = (*current)->next; 
        return head;
    }
};
python3,使用了头结点
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        tmp = head
        while n > 0:
            tmp = tmp.next
            n -= 1
        current = head
        dummy = ListNode(0)
        dummy.next = current
        prev = dummy
        while tmp != None:
            tmp = tmp.next
            current = current.next
            prev = prev.next
        prev.next = current.next
        return dummy.next
        
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号