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;
    }
};



你可能感兴趣的:(leetcode)