Arvin_JIN

双链表基本操作

#include <iostream>
using namespace std; 

typedef  int ElemType;

typedef struct DLnode{
    DLnode*prior;
    DLnode*next;
    ElemType data;
} DLinkList;


//头插法
void CreateListF(DLinkList *&list, ElemType a[], int n) {
    DLinkList *s;
    int i;
    list = (DLinkList *)malloc(sizeof(DLinkList));
    list->prior = list->next = NULL;
    for (i = 0; i < n; i++) {
        s = (DLinkList *)malloc(sizeof(DLinkList));
        s->data = a[i];
        s->next = list->next;
        if (list->next != NULL)
            list->next->prior = s;
        list->next = s;
        s->prior = list;
    }
}

//尾插法
void CreateListR(DLinkList *&list, ElemType a[], int n) {
    DLinkList *p, *s;
    list = (DLinkList *)malloc(sizeof(DLinkList));
    list->prior = list->next = NULL;
    p = list;
    for (int i = 0; i < n; i++) {
        s = (DLinkList *)malloc(sizeof(DLinkList));
        s->data = a[i];

        s->next = p->next;
        s->prior = p;
        p->next = s;
        p = s;
    }
}

// 插入数据
bool ListInsert(DLinkList *&list, int i, ElemType e) {
    int j = 0;
    DLinkList *s, *p;
    p = list;
    while (j <i -1 && p != NULL)
    {
        j++;
        p = p->next;
    }
    if (p == NULL) {
        return false;
    }
    else {
        s = (DLinkList *)malloc(sizeof(DLinkList));
        s->data = e;
        s->next = p->next;
        if (p->next != NULL) {
            p->next->prior = s;
        }
        p->next = s;
        s->prior = p;
        return true;
    }
}

//删除数据
bool Delnode(DLinkList *&list, int i, ElemType e) {
    int j = 0;
    DLinkList *p,*q;
    p = list;
    while (j < i - 1 && p != NULL) {
        j++;
        p = p->next;
    }
    if (p == NULL) {
        return false;
    }
    else {
        q = p->next;
        if (q == NULL)
            return false;
        e = q->data;
        p->next = q ->next;
        q->next->prior = p;
        free(q);
        return true;
    }

}

void DispList(DLinkList * list) {
    DLinkList *p;
    p = list->next;
    while (p != NULL) {
        cout << p->data << "  ";
        p = p->next;
    }
}


int main() {
    const int n = 7;
    int a[n];
    cout << "Input " << n << " numbers:";
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    DLinkList *lista, *listb;
    CreateListF(lista, a, n);
    CreateListR(listb, a, n);
    cout << "头(lista)";
    DispList(lista);
    cout << endl << "尾(listb)";
    DispList(listb);

    cout << endl << endl;
    int loca, m;
    cout << "输入要插入的数据和位置(lista):";
    cin >> m >> loca;
    if (ListInsert(lista, loca, m)) {
        DispList(lista);
        cout << endl << endl;
    }
    else cout << "插入失败" << endl;

    cout << "输入要删除的数据的位置(lista):";
    cin >> loca;
    if (Delnode(lista, loca, m)) {
        DispList(lista);
        cout << endl << endl;
    }
    else cout << "插入失败" << endl;

}

 

参考书籍《数据结构教程》李春葆版

posted on 2018-05-01 17:18  Arvin_JIN  阅读(232)  评论(0编辑  收藏  举报

导航