leetcode刷题,总结,记录,备忘 19

leetcode19Remove 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.

题目的提示是使用双指针,,,可是我最开始最先想到的是用递归,感觉有点非主流。。。。以前在看c和指针这本书的时候遇到一个题,将链表倒置,就是用的递归,主要思路是一路重复调用进去,到最后的节点处,然后一个一个返回。这题的思路就是递归调用,一个参数是链表节点的指针,一个参数是一个int指针,代表倒数的n个节点,先一路走到最后一个节点,然后根据n的值不断自减,然后一直返回,如果n减到0,代表该删除这个节点,就把返回的节点当作返回值返回上层,然后在上一层中链在上一层的next后面,详细看代码。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode * function(ListNode * head, int * n)
    {
        ListNode * result;
        
        if (head->next)
        {
            result = function(head->next, n);
        }
        else
        {
            result = NULL;
        }
        
        if (--*n == 0)
        {
            return result;
        }
        else
        {
            head->next = result;
            return head;
        }
    }
    
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int m = n;
        if (head == NULL)
        {
            return NULL;
        }
        
        ListNode * result = function(head, &m);
        
        return result;
    }
};
讨论区看到一个非常厉害的解决方法,用2个指针,先用一个指针走n-1个位置,然后第二个指针与第一个指针一起走,直到第一个指针为null,此时第二个指针就是要删除的节点,并且第二个指针使用的是二级指针的方式,可以直接通过二级指针的地址修改该节点上的值,非常巧妙。

class Solution
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        ListNode** t1 = &head, *t2 = head;
        for(int i = 1; i < n; ++i)
        {
            t2 = t2->next;
        }
        while(t2->next != NULL)
        {
            t1 = &((*t1)->next);
            t2 = t2->next;
        }
        *t1 = (*t1)->next;
        return head;
    }
};



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值