Remove Nth Node From End of List

直观思维先走到底得出node数目count,再从前走count - N。很明显时间复杂度2n,这是最直白最普通的思维,没有联系计算机相关数据结构知识,所以效率差。之后看了解答用了双指针,让fast先走N步然后slow再同时走,那么fast到底时slow就是目标位置。这才是计算机式的解答。

本人AC版:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
    if (n == 0)
        return head;
    int count = 0;
    struct ListNode *node = head;
    while ((node)) {
        node = node->next;
        count++;
    }
    node = head;
    if (n == count) {
        head = head->next;
        free(node);
    }
    else {
        for (int i = 0; i < count - n - 1; i++)
            node = node->next;
        struct ListNode *tmpnode = node->next;
        node->next = node->next->next;
        free(tmpnode);
    }
    return head;
}
解答nice版:

struct ListNode *fixed_removeNthFromEnd(struct ListNode *head, int n) {
    ListNode dummy = {-1, head};
    ListNode *xp = head, *yp = &dummy;
    for (int i = 1; i < n; i++)
        xp = xp->next;
    
    while (xp->next) {
        yp = yp->next;
        xp = xp->next;
    }
    
    ListNode *tmpp = yp;
    yp->next = yp->next->next;
    free(tmpp->next);
    return dummy.next;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值