19. Remove Nth Node From End of List

题目描述

leetcode刷题 19. Remove Nth Node From End of List

题目解读

  • 一开始做的时候以为一直是倒数第二个,我想这不是很容易,结果没看清题目,那个bug改的痛啊,以及要纪念一下第一次不看讨论区独立完成的代码。

代码

/**
* 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* cur = head->next;
    ListNode* pre = head;
    int num = 0;
    while(pre!=nullptr)
    {
        num++;
        pre = pre->next;
    }
    cout<<num<<endl;
    pre = head;
    
    int i = 0;
    if(num == 1 && n == 1) return nullptr;   // 当n=num=1,就是空的了
    else if(num < n) return nullptr;    
    else if(num == n)
    {
        // cout<<"**"<<endl;
        head = pre->next;
        return head;
    }
    while(i < num-n-1 )
    {
        
        pre = cur;
        cur = cur->next;
        i++;
        // cout<<pre->val<<":"<<cur->val<<endl;
    }
    pre->next = cur->next;
    return head;   
}
};

相关文章:

  • 2021-11-23
  • 2021-07-13
  • 2021-07-16
  • 2021-05-16
  • 2021-07-16
  • 2022-02-16
猜你喜欢
  • 2021-08-25
  • 2022-12-23
  • 2021-10-13
  • 2021-09-02
  • 2022-01-03
  • 2021-08-18
  • 2021-10-31
相关资源
相似解决方案