2.2 单链表的插入与删除

LinkList.h

#pragma once
#include <iostream>
using namespace std;
class LNode {
    friend class LinkList;
    int data;
    LNode* next;
};
class LinkList {
private:
    LNode* first;
public:
    LinkList() {
        first = new LNode();
        first->data = 666;
        first->next = nullptr;
    }
    void show() {
        LNode* p;
        p = first->next;
        int i = 0;
        while (p!= nullptr) {
            cout << i << ":";
            cout << p->data << " ";
            i++;
            p = p->next;
        }
        putchar('\n');

    }
    void insert(int index, int e) {
        LNode* p = new LNode();
        LNode* q = first;
        p->data = e;
        for (int i = 0; i < index; i++) {
            q = q->next;
        }
        p->next = q->next;
        q->next = p;
    }
    void remove(int index) {
        LNode* p = first;
        for (int i = 0; i < index; i++) { 
            p = p->next;
        }
        cout << "删除的是:" << p->next->data << endl;
        p->next = p->next->next;
    }
};

main:

#include"LinkList.h"
int main() {
    LinkList L;
    L.insert(0, 9);
    L.insert(0, 8);
    L.insert(1, 6);
    L.insert(2, 98);
    L.show();
    L.remove(0);
    L.show();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SlowIsFast/p/12453905.html
2.2