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++放的位置了。

相关推荐
_日拱一卒5 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
2401_868534787 小时前
【无标题】
数据结构·r语言
Mr. zhihao7 小时前
Redis五大高级数据结构:原理-场景-底层-横向对比
数据结构·redis
QiLinkOS7 小时前
【从实验室到商业战场:发明专利如何重塑科技与企业的共生生态】
大数据·c语言·数据结构·c++·人工智能·单片机·算法
如此这般英俊8 小时前
手撕Claude Code—第一章 agent-loop
数据结构·人工智能·语言模型·自然语言处理
过期动态9 小时前
【LeetCode 热题 100】接雨水
java·数据结构·算法·leetcode·职场和发展
青山师10 小时前
动态规划算法深度解析:从状态转移方程到工业级优化
数据结构·算法·面试·动态规划·代理模式·java面试
Severus_black12 小时前
【初阶数据结构与算法】八大排序之非比较排序(计数排序),一次性讲清!
数据结构·算法·排序算法
QiLinkOS12 小时前
从技术到资产的跃迁:企业专利布局的深层逻辑
c语言·数据结构·c++·单片机·嵌入式硬件·算法·开源
磊 子13 小时前
STL之deque和list以及两者与vector的对比
开发语言·c++·list