#19 Remove Nth Node From End of List(删除链表倒数第N个节点)

#19 Remove Nth Node From End of List

题目地址:#19
题目分类:Linked List(链表)
题目难度:Easy


题目

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.


思路

简单题,唯一难点是:在一次遍历中完成这个过程。
因此我们选择用两个指针的方法,一个指针先走N步,在考虑边界条件的同时遍历链表。
要点:删除倒数第N个,维护的应该是这个节点的前一个。此为解题关键


陷阱

1 边界条件,容易犯N差1的错误
2 对于链表长度恰好为N,要注意单独处理
3 链表计数,是从1开始,同样边界条件问题
4 题目要求删除倒数第N个,并非正数


测试案例

1 空链表。应该返回NULL
2 输入n == 0,应该不做任何改动
3 链表长为N,输入n == N
4 链表长为N,输入n > N
5 正常输入


代码

C
(双指针,不引入额外节点,以循环计数控制边界条件。较容易出+-1错误,不推荐)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
    if(head==NULL||n==0)
        return head;
    struct ListNode *fast = head;
    int i;
    for(i=0;i<n-1;i++){
        if(fast->next==NULL)
            return head;//wrong input, n too big
        fast = fast->next;
    }
    if(fast->next==NULL)
        return head->next;
    fast = fast->next;
    //dealing with when length equals n

    struct ListNode *ptr_before_delete = head;
    while(fast->next!=NULL){
        fast = fast->next;
        ptr_before_delete = ptr_before_delete->next;
    }
    ptr_before_delete->next = ptr_before_delete->next->next;
    return head;
}

/*
1- n bigger than length
2- nothing else, pay attention to the way counting n
3- damn, from the end. I ignore that
*/

C++
(小改动,引入额外节点作为头结点。方便计数,代码简洁。如果允许额外节点空间,推荐这种方法。为了代码简洁,并没有delete这个额外节点,实际使用记得删掉)

/**
 * 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 *realhead=new ListNode(0);
        realhead->next=head;
        ListNode *fast=realhead,*slow=realhead;
        while(n--)
        {
            if(fast==NULL)//n>length, return
                return head;
            fast=fast->next;
        }
        while(fast->next!=NULL)//fast move to the last node
        {
            fast=fast->next;
            slow=slow->next;
        }
        slow->next=slow->next->next;//not good but for shorter time
        return realhead->next;        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值