leetcode #19 in cp

The question is to remove the nth node from the end of a linked list.

Solution:

        One solution is to use two pointers. The idea is to keep two pointers with a distance n between them. When one pointer reach the end, the other pointer is the parent of the node we are to remove. 

  One example is to remove the 2nd node from the end of  a linked list [1,2,3,4,5], which here is 4. 

        step1: first keep two pointers,p1, p2, initially at the head: 1(p1, p2), 2, 3, 4, 5. 

        step2: We want to keep a distance of 2 between them. So now we move p2 2 steps further, and it becomes: 1(p1), 2, 3(p2), 4, 5.

step3: Now we iterate, and each iteration moves p1 and p2 1 step toward the end. Iterations stop when p2 reach the end( see if p2->next == NULL. If so then p2 now is the end): 

           iteration 1: 1, 2(p1), 3, 4(p2), 5  

           iteration 2: 1, 2, 3(p1), 4, 5(p2)  

           p2 is at the end and we stop. 

        step4: Now p1 is the parent of the node, 4,  we are to remove. Thus we make p1->next = p1->next-next;

One trouble for this question is the boundary problem: the head is the one we want to remove. In this case we cannot use p1->next = p1->next->next. One thing we can see in this case is that if the head is the one we want to remove, or n == length of the linked list, p2 would reach the end in step 2. Otherwise p2 would not reach the end. Thus in step 2 we add one condition to check if p2 reaches the end. If so we just remove the head, and return head->next.

Code:

/**
 * 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 *p1 = head;
        ListNode *p2 = head;
        while(n > 0){
            if(p2->next == NULL){
                return head->next;
            }
            p2 = p2->next;
            n--;
        }
        while(p2->next != NULL){
            p2 = p2->next;
            p1 = p1->next;
        }
        p1->next = p1->next->next;
        return head;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值