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

相关推荐
haokan_Jia14 小时前
【java使用LinkedHashMap进行list数据分组写入,顺序并没有按照原始顺序,原因分析】
java·开发语言·list
C雨后彩虹14 小时前
中文分词模拟器
java·数据结构·算法·华为·面试
Remember_99314 小时前
【LeetCode精选算法】二分查找专题二
java·数据结构·算法·leetcode·哈希算法
学嵌入式的小杨同学15 小时前
【嵌入式 C 语言实战】栈、队列、二叉树核心解析:存储原理 + 应用场景 + 实现思路
linux·c语言·网络·数据结构·数据库·后端·spring
2401_8414956415 小时前
【LeetCode刷题】删除链表的倒数第N个结点
数据结构·python·算法·leetcode·链表·遍历·双指针
苦藤新鸡15 小时前
28.两数相加,进位制
数据结构·算法·链表·力扣
无限进步_15 小时前
二叉搜索树(BST)详解:从原理到实现
开发语言·数据结构·c++·ide·后端·github·visual studio
wangjialelele16 小时前
二刷C语言后,一万字整理细碎知识点
c语言·开发语言·数据结构·c++·算法·cpp
Stardep16 小时前
算法入门21——二分查找算法——山脉数组的峰顶索引
数据结构·算法·leetcode
橘颂TA16 小时前
【剑斩OFFER】算法的暴力美学——力扣 675 题:为高尔夫比赛砍树
数据结构·算法·c·结构与算法