19. Remove Nth Node From End of List

Posted doudouyoutang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19. Remove Nth Node From End of List相关的知识,希望对你有一定的参考价值。

一、问题描述

  给定一个链表的数据结构和链表的头结点,和正整数N,要求删除倒数第N个结点技术分享图片

二、思路

  删除链表的一个结点,如果你只有当前结点,可以将下一个结点的值赋值到当前结点,然后删除下一个结点就可以。

  如果你能找到需要删除结点的上一个结点,那么你可以直接操作上一个结点的指针指向下下一个结点就可以

  利用两个指针,两个指针中间间隔N个结点的长度,同时往链表末端移动,当后面的指针移动到末端的时候,前面的指针指向需要删除的结点。

  注意:考虑到要删除头结点,可以构造一个虚假的结点

 

四、代码

  

/**
 * 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 || n <= 0)
        {
            return head;
        }
        
        ListNode *fake_head = new ListNode(-1);
        fake_head->next = head;
        
        ListNode *fast = fake_head;
        ListNode *slow = NULL;
        
        for (int i = 1; i <= n && fast->next != NULL; i++) {
            
            fast = fast->next;
            
            if(i == n)
            {
                //确认链表的长度大于等于N
                slow = fake_head;
            }
            
        }
        
        while (fast->next) {
            
            fast = fast->next;
            slow = slow->next;
        }
        
        
        if(slow)
        {
            //找到了上一个结点
            slow->next = slow->next->next;
        }
        
        
        return fake_head->next;
        
    }
};

  

以上是关于19. Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章

LC_19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

[LeetCode19]Remove Nth Node From End of List

19. Remove Nth Node From End of List