C++ 删除链表倒数第k个结点

C++ 删除链表倒数第k个结点,第1张

#include 
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x), next(nullptr){}
};
class solution{
public:
    ListNode *remove(ListNode *head, int k){
        //fast先移动k个结点,这样当fast->next=nullptr时,slow->next就是要删除的结点
        ListNode *fast = head, *slow = head, *p = head;
        int size = 0;
        while(p){
            p = p -> next;
            ++size;
        }
        if(k == size ){
            head = head -> next;
        }
        else if(k == 1 && fast -> next == nullptr){
            delete head;
            return nullptr;
        }
        else{
            while(k > 0 && fast -> next != nullptr){
                fast = fast -> next;
                --k;
            }
            while(fast -> next != nullptr){
                fast = fast -> next;
                slow = slow -> next;
            }
            slow -> next = slow -> next -> next;
        }
        return head;
    }
};


int main(){

    ListNode *head = new ListNode(0);
    ListNode *p = head;
    for(int i = 1; i < 10; ++i ){
        ListNode *temp = new ListNode(i);
        p -> next = temp;
        p = p -> next;
    }
    p = head;
    solution s;
    s.remove(p,2);
    p = head;
    while(p != nullptr){
        cout << p -> val;
        p = p -> next;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/2889671.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-14
下一篇 2022-09-14

发表评论

登录后才能评论

评论列表(0条)

保存