19.删除链表的倒数第N个结点

#include <iostream>
using namespace std;

  struct ListNode {
      int val;
    ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };
 
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) 
    {
        int count = 1;
        ListNode* first = head;
        ListNode* second = head;
        ListNode* p = head;
        while (first && count <= n)
        {
            count++;
            first = first->next;
        }
        if (first==NULL)         //处理边界条件的情况,若删除的是首位或末位,则直接由头指针指向下一个元素
            return head->next;
        while (first!=NULL)
        {
            p = second;
            first = first->next;
            second = second->next;
        }
       
        p->next = second->next;
        return head;
    }
}; 

提交过后如出现错误,应该在草稿纸上模拟指针的前进过程,从而可以发现问题。

猜你喜欢

转载自blog.csdn.net/m0_51177881/article/details/117195273
今日推荐