174. 删除链表中倒数第n个节点

174. 删除链表中倒数第n个节点
 

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。


样例

Example 1:
    Input: list = 1->2->3->4->5->null, n = 2
    Output: 1->2->3->5->null


Example 2:
    Input:  list = 5->4->3->2->1->null, n = 2
    Output: 5->4->3->1->null

挑战

O(n)时间复杂度
注意事项

链表中的节点个数大于等于n

ListNode * removeNthFromEnd(ListNode * head, int n) {
        // write your code here
        
        if(NULL == head)
        {
            return head;
        }
        
        ListNode *front=head;
        ListNode *back=head;
        while(n>0)
        {
            n--;
            if(NULL == front)
            {
                return NULL;
            }
            front=front->next;
            
        }
        //删除头部
        if(NULL == front)
        {
            return head->next;
        }

        front=front->next;
        while(front)
        {
            back=back->next;
            front=front->next;
        }
      
        back->next = back->next->next;
        return head;
    }

扫描二维码关注公众号,回复: 12285845 查看本文章

猜你喜欢

转载自blog.csdn.net/yinhua405/article/details/112976715