LeetCode - 19. Remove Nth Node From End of List

问题

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {

        ListNode** arr = new ListNode*[n + 1];   //注意是 ListNode** arr,指向指针数组的指针
        ListNode *p = head;                      //参考:http://blog.youkuaiyun.com/g200407331/article/details/52610150
        int index = 0;
        int full = 0;
        while(p)
        {
            index = index % (n+1);
            arr[index++] = p;
            p = p->next;
            if(index == n+1) full = 1;
        }
        if(!full) return head->next;    //if not full, meaning head node is to be deleted
        ListNode* to_be_deleted = arr[index % (n+1)]->next;
        arr[index % (n+1)]->next = arr[(index+1)%(n+1)]->next;
        delete to_be_deleted;
        delete []arr;
        return head;
    }

    //高分参考答案,优点是空间复杂度低,不像我的方法定义一个动态数组,只用一快一慢两个指针就搞定;
    //缺点是没删除那个被去掉的节点,内存泄漏。
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        ListNode** t1 = &head, *t2 = head;  //对比前面的ListNode**,指向指针的指针
        for(int i = 1; i < n; ++i)
        {
            t2 = t2->next;
        }
        while(t2->next != NULL)
        {
            t1 = &((*t1)->next);
            t2 = t2->next;
        }
        *t1 = (*t1)->next;  //左边的*t1实际是前一个节点的next域,该next域本来是指向当前节点,
        return head;        //现在等于当前节点的next域了,也就是指向了下一个节点。这种写法实际上不好理解
    }

    //高分参考答案2,无内存泄漏问题
    //可谓最佳答案,好理解。
    ListNode *removeNthFromEnd(ListNode *head, int n) 
    {
    if (!head)
        return nullptr;

    ListNode new_head(-1);  //定义了一个伪根,很有帮助
    new_head.next = head;
    ListNode *slow = &new_head, *fast = &new_head;

    for (int i = 0; i < n; i++)
        fast = fast->next;

    while (fast->next) 
    {
        fast = fast->next;
        slow = slow->next;
    }

    ListNode *to_de_deleted = slow->next;
    slow->next = slow->next->next;

    delete to_be_deleted;

    return new_head.next;
    }
};

总结

  • 对于这种要剔除链表第几个节点的问题,定义一快一慢两个指针是经常做法;
  • 链表问题,有时候定义一个伪根,能够简化问题;
  • 指针与指向指针的指针是容易混淆的概念,需常常回顾。
  • 可参考博客:理解一般指针和指向指针的指针
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值