• 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?

    1.傻瓜办法:

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. ListNode* removeNthFromEnd(ListNode* head, int n) {
    14. ListNode*curr=head;
    15. int count=0;
    16. while(curr!=NULL){
    17. count++;
    18. curr=curr->next;
    19. }
    20. int cnt=count-n+1;
    21. struct ListNode*dummyHead=new ListNode(0,head);
    22. struct ListNode*pre=dummyHead;
    23. count=0;
    24. while(pre->next!=NULL){
    25. count++;
    26. if(count==cnt){
    27. pre->next=pre->next->next;
    28. }else{
    29. pre=pre->next;
    30. }
    31. }
    32. ListNode*ret=dummyHead->next;
    33. delete dummyHead;
    34. return ret;
    35. }
    36. };

    注意:

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

    2.快慢指针:

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. ListNode* removeNthFromEnd(ListNode* head, int n) {
    14. ListNode*dummyHead=new ListNode(0,head);
    15. ListNode*fast=dummyHead;
    16. ListNode*slow=dummyHead;
    17. n++;
    18. while(n--)fast=fast->next;
    19. while(fast!=NULL){
    20. fast=fast->next;
    21. slow=slow->next;
    22. }
    23. slow->next=slow->next->next;
    24. ListNode*temp=dummyHead->next;
    25. delete dummyHead;
    26. return temp;
    27. }
    28. };

    注意:

            1.中心思想:fast比slow多走n步,但是这会导致slow最后指向的位置刚好是要删除的,所以fast应该比slow多走n+1步,保证当fast==NULL的时候,slow是要被删除的倒数第n个位置的前一个位置。(fast和slow始终距离n+1)

            2.C++代码要手动释放new的节点内存

  • 相关阅读:
    JAVA 基础学习笔记 (6)访问权限修饰符
    Linux命令--在后台运行程序--方法/实例
    Java中将字符串ArrayList转换为数组的四种方法
    Logstash实现MySql数据近实时同步ElasticSearch搜索服务
    用递归函数和栈操作逆序栈
    PHP即刻送达同城派送小程序系统
    STM32解析航模遥控器的PPM信号
    使用 Vite 插件开发构建 Tampermonkey 用户脚本
    平衡二叉树基本操作(AVL平衡二叉树)
    REVA再创NFT托管新记录!Boodles等企业相继入局
  • 原文地址:https://blog.csdn.net/2301_80161204/article/details/139829172