19. Remove Nth Node From End of List

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个结点到最后一个结点总共有n+1个结点。于是可是设计算法如下:

DeleteNode最终指向倒数第n+1个结点

<span style="font-family: Arial, Helvetica, sans-serif;">CurrNode指向当前结点</span>
当<span style="font-family: Arial, Helvetica, sans-serif;">CurrNode遍历到正向第n+1个结点的时候,令<span style="color: rgb(255, 0, 0); font-size: 18px; background-color: rgb(240, 240, 240);">DeleteNode指向第一个结点,然后两个指针同步后移!</span></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: rgb(255, 0, 0); font-size: 18px; background-color: rgb(240, 240, 240);">当</span></span><span style="font-family: Arial, Helvetica, sans-serif;">CurrNode遍历到最后一个结点的时候,DeleteNode就正好指向倒数</span><span style="font-family: Arial, Helvetica, sans-serif;">第n+1个结点!</span>
<span style="font-family: Arial, Helvetica, sans-serif;">利用</span><span style="font-family: Arial, Helvetica, sans-serif;">DeleteNode->next=</span><span style="font-family: Arial, Helvetica, sans-serif;">DeleteNode->next->next;删除结点!</span>



我的答案:

/**
 * 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) {
        if(head==NULL)return head;
        ListNode *CurrNode=head;//遍历链表,CurrNode指向当前结点,DeleteNode指向 从CurrNode往前数n个结点
        int count=0;
        while(CurrNode!=NULL&&count!=n){
            CurrNode=CurrNode->next;
            count++;
        }
        if(count==n&&CurrNode==NULL)head=head->next;//链表共有n个结点,删除头结点
        else if(count==n&&CurrNode!=NULL){//CurrNode结点和DeletNode结点同步向下一个结点移动,两者之间相隔n个结点。当CurrNode结点走到终点时,利用DeleteNode删除需要删除的结点
            ListNode *DeleteNode=head;
            while(CurrNode->next!=NULL){
                CurrNode=CurrNode->next;
                DeleteNode=DeleteNode->next;
            }
            DeleteNode->next=DeleteNode->next->next;//删除结点
        }
        return head;
    }
};


你可能感兴趣的:(LeetCode,C++)