• 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的节点内存

  • 相关阅读:
    【Netty】第3章-Java NIO 编程
    企业微信机器人对接GPT
    sort方法实现复杂排序
    【电源设计】10功率MOSFET在开关电源中的应用
    「AI知多少」第二期推荐《AIGC:智能创作时代》
    LVS负载均衡群集+NAT部署
    分布式开发漫谈
    MapReduce的编程开发-合并
    java毕业设计网站swing mysql实现的工程项目管理系统[包运行成功]
    【JavaSE】Java方法
  • 原文地址:https://blog.csdn.net/2301_80161204/article/details/139829172