19. 删除链表的倒数第N个节点/C++

19. 删除链表的倒数第N个节点/C++_第1张图片
由于题目说n保证有效,因此可以剩下不少麻烦。
就是用两个指针,第1个指针先走n,第2个指针再与第1个指针一起走,当第1个指针到队尾时,第2个指针就指向要删掉的节点。
当然其中细节还很多,比如第2个指针实际上要指的是删除节点的前一个节点。

ListNode* removeNthFromEnd(ListNode* head, int n) {
	//如果链表没有节点或者只有1个节点,直接返回null
    if(!head || !head->next) return nullptr;
    
    ListNode* first = head;
    for(int i=0;i<n;++i)
        first=first->next;
    //如果first为null,就说明要删掉的是第一个节点,可以直接返回
    if(!first) return head->next;
    
    ListNode* second = head;
    while(first->next){
        first=first->next;
        second=second->next;
    }
    if(second->next)
        second->next=second->next->next;
    else
        second->next=nullptr;
    return head;
}

你可能感兴趣的:(双指针,LeetCode/C++)