欢迎光临散文网 会员登陆 & 注册

19. 删除链表的倒数第 N 个结点

2023-04-02 15:30 作者:薄荷硬糖酱  | 我要投稿

19. 删除链表的倒数第 N 个结点

难度中等2492

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

 

示例 1:

输入:head = [1,2,3,4,5], n = 2输出:[1,2,3,5]

示例 2:

输入:head = [1], n = 1输出:[]

示例 3:

输入:head = [1,2], n = 1输出:[1]

 

提示:

  • 链表中结点的数目为 sz

  • 1 <= sz <= 30

  • 0 <= Node.val <= 100

  • 1 <= n <= sz

 

进阶:你能尝试使用一趟扫描实现吗?

第一种法:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){

    struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));

    newhead->next = head;

    struct ListNode *cur = newhead;

    struct ListNode *last = cur;

    while(1){

        for(int i=0;i<n;i++){

            last = last->next;

        }

         if(last->next==NULL){

            struct ListNode* tmp = cur->next;

            cur->next = last;

            free(tmp);

            return newhead->next;

        }else{

            cur=cur->next;

            last = cur;

        }

    }

}

这里的last是只考虑了n是偶数的情况,当n为奇数时last将指向需要删除的元素,与循环中的代码矛盾。

第一种法:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */


struct ListNode* removeNthFromEnd(struct ListNode* head, int n){

    struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));

    newhead->next = head;

    struct ListNode *cur = newhead;

    struct ListNode *last = cur;

    while(1){

        for(int i=0;i<=n;i++){

            last = last->next;

        }

         if(last==NULL){

            struct ListNode* tmp = cur->next;

            cur->next = cur->next->next;

            free(tmp);

            return newhead->next;

        }else{

            cur=cur->next;

            last = cur;

        }

    }

}


19. 删除链表的倒数第 N 个结点的评论 (共 条)

分享到微博请遵守国家法律