LeetCode OJ-19.Remove Nth Node From End of List

LeetCode OJ-19.Remove Nth Node From End of List

题目描述

Given a linked list, remove the *n*th 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个节点。虽然处理起来很直接,但还是要注意一些细节:在删除节点时,若待删除节点为表头节点,则直接返回head->next即可;若为表的中部节点,即该节点存在前驱后继节点,则要将其前驱节点的next值赋值为其后继节点;若为表尾节点,则将其前驱节点的next设置为空指针即可。至于位置的确定,可以用倒数链表长度的方式处理,具体的处理可以参考代码,细节也在注释中表明了。

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

int list_cnt(ListNode *head) {
    ListNode *cur = head; 
    int res = 0; 
    while (cur != 0) {
        cur = cur->next; 
        ++res; 
    } 

    return res; 
}

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int sz = list_cnt(head); 
        int pos = sz; 
        if (pos == n) {  // 去除表头节点的情况 
            return head->next; 
        } 
        else {  // 去除表头以外的节点的情况 
            ListNode *last = head; 
            ListNode *cur = head; 
            while (pos != n) {
                last = cur; 
                cur = cur->next; 
                --pos;  // 倒数链表长度即可得到待删除节点的位置,这点可以自己写写验证下 
            } 

            if (cur->next != 0) {  // 待去除节点后继节点存在 
                last->next = cur->next; 
            } 
            else {  // 待去除节点为表尾 
                last->next = 0; 
            }
        } 

        return head; 
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值