leetcode 19. Remove Nth Node From End of List

Posted 去做点事情

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 19. Remove Nth Node From End of List相关的知识,希望对你有一定的参考价值。

 

这个题和剑指上的倒数第k个结点略微有点不一样,找到倒数第k个只需要移动n-1次,但删除倒数第k个需要移动n次,因为需要找到倒数第k个后面那个

还有如果k值大于等于了长度,返回的是head的next

注意p2->next = p2->next->next

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head == NULL || n <= 0)
            return NULL;
        ListNode* p1 = head;
        ListNode* p2 = head;
        int num = n;
        while(num != 0){
            p1 = p1->next;
            num--;
        }
        if(p1 == NULL)
            return head->next;
        while(p1->next != NULL){
            p1 = p1->next;
            p2 = p2->next;
        }
        p2->next = p2->next->next;
        return head;
    }
};

https://www.cnblogs.com/grandyang/p/4606920.html

以上是关于leetcode 19. Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章

leetcode19. Remove Nth Node From End of List

LeetCode 19. Remove Nth Node From End of List

LeetCode-19-Remove Nth Node From End of List

leetcode 之Remove Nth Node From End of List(19)

LeetCode19- Remove Nth Node From End of List-Medium

LeetCode19- Remove Nth Node From End of List-Medium