19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:

复制代码
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

复制代码
Input: head = [1], n = 1
Output: []

Example 3:

复制代码
Input: head = [1,2], n = 1
Output: [1]

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Follow up: Could you do this in one pass?

复制代码
/**
 * Definition for singly-linked list.
 * 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) {
        ListNode*curr=head;
        int count=0;
        while(curr!=NULL){
            count++;
            curr=curr->next;
        }
        int cnt=count-n+1;
        struct ListNode*dummyHead=new ListNode(0,head);
        struct ListNode*pre=dummyHead;
        count=0;
        while(pre->next!=NULL){
            count++;
            if(count==cnt){
                pre->next=pre->next->next;
            }else{
                pre=pre->next;
            }
        }
        ListNode*ret=dummyHead->next;
        delete dummyHead;
        return ret;
    }
};

注意:

我的这种方法是最容易想到的,先遍历一遍链表得到链表长度,需要注意的一点只有count++放的位置了。

相关推荐
quaer8 小时前
弗洛伊德算法--判圈法寻找环的入口O(n) O(1)
数据结构·算法
xys_67812 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法
BeiGuTing_code12 小时前
Java动态数组(一)
java·数据结构·windows
Code_Solitude15 小时前
传智杯备赛代码整理(前4题)
数据结构·算法
Jasmine_llq16 小时前
《P8816 [CSP-J 2022] 上升点列》
数据结构·算法·贪心·排序·二维动态规划 dp·类背包状态转移
辛苦才能16 小时前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
JasmineX-117 小时前
数据结构(笔记)——顺序栈
c语言·数据结构·笔记
凉茶钱18 小时前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
敲代码的苦1320 小时前
头歌数据结构-排序的实现及其应用
数据结构
有同事要进步20 小时前
Leecode第68题:x的平方根
java·数据结构·算法