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

相关推荐
Genevieve_xiao1 小时前
【数据结构】【xjtuse】八股文单元小测
数据结构·算法
想唱rap3 小时前
Linux下进程的状态和优先级
linux·运维·服务器·开发语言·数据结构·算法
Croa-vo4 小时前
逆袭Akuna Quant!美硕秋招亲历,从网申到拿offer全攻略
数据结构·经验分享·算法·面试·职场和发展
vir025 小时前
交换瓶子(贪心)
数据结构·算法
952366 小时前
数据结构-二叉树
java·数据结构·学习
HUTAC7 小时前
重要排序算法(更新ing)
数据结构·算法
冉佳驹7 小时前
数据结构 ——— 八大排序算法的思想及其实现
c语言·数据结构·排序算法·归并排序·希尔排序·快速排序·计数排序
Hello_Embed8 小时前
FreeRTOS 入门(四):堆的核心原理
数据结构·笔记·学习·链表·freertos·
烧冻鸡翅QAQ9 小时前
考研408笔记——数据结构
数据结构·笔记·考研
异步的告白9 小时前
C语言-数据结构-2-单链表程序-增删改查
c语言·开发语言·数据结构