zoukankan      html  css  js  c++  java
  • 19. 删除链表的倒数第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) {
          ListNode* slow = head,*fast=head;
           
            for(int i=0;i<n;i++)
            {
                fast = fast->next;
            }
            //如果删除的是第一个元素
            if(fast==NULL)
            {
                ListNode* tem = head;
                head = head->next;
                delete tem;
                return head;
            }
            
            while(fast->next)
            {
                fast = fast->next;
                slow = slow->next;
            }
            //最后停止的时候,慢的指针指向的是要删除的点之前那个元素
            ListNode* tem = slow->next;
            slow->next = slow->next->next;
            delete tem;
    
            return head;
            
        }
    };

    思路

    先用一个快指针前进n步,当快指针的下一个是nullptr时,慢指针的下一个则是要删除的元素

    https://github.com/li-zheng-hao
  • 相关阅读:
    poj2263
    poj2304
    低调是态度,也是智慧
    股票操作記錄2
    治病記錄(2013年)
    过年了
    治病記錄
    近段時間學習記錄
    新的一年
    關于設計
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053634.html
Copyright © 2011-2022 走看看