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

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

样例

给出链表1->2->3->4->5->null和 n = 2.

删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.

分析:考虑到鲁棒性 每一种情况都要考虑到 尤其是在删除的是尾节点时 刚开始就没考虑到尾节点。

/**
 * 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) {
        // write your code here
        if(head==NULL)
        return 0;
        if(head->next==NULL&&n==1)
        return 0;
        ListNode *p1=head;
        ListNode *p2=NULL;
        ListNode *pre=NULL;
        for(int i=0;i<n-1;i++)
        {
            if(p1->next!=NULL)
            {
                p1=p1->next;
            }
            else
              return NULL;
        }
        p2=head;
        while(p1->next!=NULL)
        {
            p1=p1->next;
            pre=p2;
            p2=p2->next;
        }
        if(p2->next==NULL)
        {
            pre->next=NULL;
            delete p2;
            p2=NULL;
        }
        else
        {
            ListNode *p3=p2->next;
            p2->val=p3->val;
            p2->next=p3->next;
            delete p3;
            p3=NULL;
        }
        return head;
    }
};

  

原文地址:https://www.cnblogs.com/lelelelele/p/6119668.html