您的位置:首页 > 其它

删除链表中倒数第n个节点

2017-03-22 22:17 295 查看
1、问题描述

      给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。给出链表1->2->3->4->5->null和
n = 2.删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.

2、实现思路

     先计算链表的长度,用for循环找到要删的节点, 要考虑链表长度<n和当长度=n时,实际上删除的是头结点 。

3、代码

/**

 * Definition of ListNode

 * class ListNode {

 * public:

 *     int val;

 *     ListNode *next;

 *     ListNode(int val) {

 *         this->val = val;

 *         this->next = NULL;

 *     }

 * }

 */

class Solution {

public:

    /**

     * @param head: The first node of linked list.

     * @param n: An integer.

     * @return: The head of linked list.

     */

     ListNode *removeNthFromEnd(ListNode *head, int n) {

        ListNode *x = head;  

        ListNode *l = head;  

        int count=0;  

        while(head!=NULL){  

            head = head->next;  

            count++;  

        } 

        if(count<n)  

            return x;

        if(count>n)

             {      

                for(int i=1;i<(count-n);i++)

                {  

                  l = l->next;  

                }  

             l->next=l->next->next;  

             return x;  

            }  

            if(count==n){  

            return x->next;  

        }  

    }  

};  

4、感想

     本题和链表倒数第n个节点想法相似,只是多了删除操作,并且要注意链表长度比n短和链表只有头结点终端节点情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: