线性表——链式存储结构之单链表

来源:互联网 发布:软件下载安装教程 编辑:程序博客网 时间:2024/06/04 17:54
#ifndef LINKLIST_H#define LINKLIST_H#include <stdint.h>#include <stdio.h>#include <stdlib.h>template <typename ElemType>class Node {public:    Node() : data(ElemType()), next(NULL) {}    Node(const ElemType &_data) : data(_data), next(NULL) {}    Node(const ElemType &_data, Node<ElemType> *_next) : data(_data), next(_next) {}    ~Node() {}public:    ElemType data;    Node<ElemType> *next;};template <typename ElemType>class SingleList {public:    SingleList() : count(0) {        if((head_node = new Node<ElemType>) == NULL)            return;        head_node->data = 0;        head_node->next = NULL;    }    ~SingleList() {        if (count != 0) {            ClearList();        }        if (head_node)        {            delete head_node;            head_node = NULL;        }    }public:    void InitList() {        count = 0;        head_node->data = 0;        head_node->next = NULL;    }    bool ListEmpty() {        return count == 0;    }    void ClearList() {        Node<ElemType> *p, *q;        p = head_node->next;        while (p) {            q = p->next;            delete p;            p = q;        }        head_node->next = NULL;        count = 0;    }    void GetElem(uint32_t i, ElemType *e) {        if ((i < 1) || (i > count)) {            fprintf(stderr, "Out of list!\n");            return;        } else {            Node<ElemType> *p = head_node;            for (int j = 0; j < i; ++j) {                p = p->next;            }            *e = p->data;        }    }    uint32_t LocateElem(ElemType e) {        Node<ElemType> *p = head_node->next;        for (int i = 1; i <= count; ++i) {            if ((p != NULL) && (p->data == e)) {                return i;            }            p = p->next;        }        fprintf(stderr, "Not in this list\n");        return -1;    }    void ListInsert(uint32_t i, ElemType *e) {        if ((i < 1) || (i > count+1)) {            fprintf(stderr, "Out of the list\n");            return;        } else {            Node<ElemType> *p = head_node;            Node<ElemType> *q = new Node<ElemType>;            q->data = *e;            for (int j = 1; j < i; ++j) {                p = p->next;            }            q->next = p->next;            p->next = q;        }        ++count;    }    void ListDelete(uint32_t i, ElemType *e) {        if ((i < 1) || (i > count+1)) {            fprintf(stderr, "Out of the list\n");            return;        }        Node<ElemType> *p, *q;        p = head_node;        for (uint32_t j = 0; j < i; ++j) {            q = p;            p = p->next;        }        q->next = p->next;        *e = p->data;        --count;        delete p;    }    uint32_t ListLength(void) {        return count;    }private:    int count;    Node<ElemType> *head_node;};#endif


后记:测试的时候,发现删除一个元素时,会导致整个链表被破坏了,在纸上画了半天,百思不得其解,最终将delete换成free,发现结果正确了,想到delete与free的区别,就意识到错哪了,竟然在Node的析构函数中,随手将next指针delete掉了。细节决定一切!


0 0