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

相关推荐
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1231 天前
【数据结构】二叉树的概念
数据结构·二叉树
凯子坚持 c1 天前
精通 Redis list:使用 redis-plus-plus 的现代 C++ 实践深度解析
c++·redis·list
第七序章2 天前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode