2.4 双链表操作

DoubleList.h

#pragma once
#include<iostream>
using namespace std;

class LNode {
    friend class DoubleList;
private:
    int data;
    LNode* before, * next;
};
class DoubleList {
private:
    LNode* first;
public:
    DoubleList() {
        first = new LNode();
        first->before = nullptr;
        first->next = nullptr;
        first->data = 666;
    }
    void creatH(int arr[], int n) {
        LNode* s;
        for (int i = 0; i < n; i++) {
            s = new LNode();
            s->data = arr[i];
            s->before = first;
            s->next = first->next;
            first->next = s;
        }
    }
    void creatE(int arr[], int n) {
        LNode* s;
        LNode* p = first;
        while (p->next!=nullptr) {
            p = p->next;
        }
        
        for (int i = 0; i < n; i++) {
            s = new LNode();
            s->data = arr[i];
            s->before = p;
            s->next = p->next;
            p->next = s;
            p = s;
        }
    }
    void show() {
        LNode* p;
        p = first->next;
        while (p) {
            cout << p->data << " ";
            p = p->next;
        }
        putchar('\n');
    }
    int search(int elem) {
        LNode* p;
        p = first;
        int i = 0;
        while (p->next != nullptr) {
            p = p->next;
            i++;
            if (p->data == elem) {
                return i;
            }
        }
        return -1;
    }
    void insert(int index,int elem){
        LNode* p;
        LNode* s;
        p = first;
        for (int i = 0; i < index-1; i++) {
            p = p->next;
        }
        s = new LNode();
        s->data = elem;
        s->before = p;
        s->next = p->next;
        p->next->before = s;
        p->next = s;
    }
    void remove(int index) {
        LNode* p;
        p = first;
        for (int i = 0; i < index-1; i++) {
            p = p->next;
        }
        cout << "delete " << p->next->data << endl;
        p->next->next->before = p;
        p->next = p->next->next;
    }
};

main.cpp

#include"DoubleList.h"

int main() {
    DoubleList L;
    int a[] = { 1,2,3,4,5 };
    int b[] = { 6,7,8,9,10 };
    L.creatH(a, 5);
    L.creatE(b, 5);
    L.show();
    LNode* p;
    cout << "7 is at " << L.search(7) << endl;
    L.insert(4, 99);
    L.show();
    L.remove(6);
    L.show();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SlowIsFast/p/12467284.html