Leetcode 19. 删除链表的倒数第N个节点

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

解题思路:

需要注意的就是

1)[1,2] 1

2)  [1,2] 2

3)  [1] 1

在1)和3)的情况中,待删除节点为首节点,因此pre节点为NULL,需要根据当前是否仅有一个节点做出判断,是直接返回head->next 还是返回null

而在2 中 待删除节点后面没有后继节点了。

/**
 * 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 *pre = find_pre(head,n);
 
        if(pre==NULL){
            if(head->next) head = head->next;
            else head = NULL;
        }else {
            pre->next = pre->next->next;
        }
        return head;
    }
    inline ListNode* find_pre(ListNode* head, int &n){
        ListNode *tmp = head, *pre = NULL;
        int count = 1;
        while(tmp->next){
            if(count==n){
                pre = head;
            }
            if(count>n){
                pre=pre->next;
            }
            tmp = tmp->next;
            count++;            
        }
        return pre;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值