当前位置:网站首页>leetcode 19. 删除链表的倒数第 N 个结点

leetcode 19. 删除链表的倒数第 N 个结点

2022-06-10 03:01:00 C卷卷

题目描述

https://leetcode.cn/problems/remove-nth-node-from-end-of-list/

思路

快慢指针 , 审题!!!

代码1


/** * 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) {} * }; */
 //注意审题 是倒数n个结点!!!
class Solution {
    
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    
        if(!head ||!head->next) {
    
            return NULL;
        }
        ListNode *fast = head, *slow = head;
        for(int i = 0; i < n; i ++) {
    
            fast = fast -> next;// fast比slow先走n步
        }
        if(fast == NULL) {
     // 删除头结点
            return head->next;
        }
        while(fast -> next) {
    
            fast = fast->next;
            slow = slow->next;
        }
        slow ->next= slow->next->next;
        return head;
    }
};

感谢阅读

原网站

版权声明
本文为[C卷卷]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_49486457/article/details/124974613