栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++链表模板化设计

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++链表模板化设计

为了节约篇幅,对其他意义不大,并且容易通过现有List类函数得到实现的函数不做定义。如前驱、后续、判空、判满、在头部插入、在尾部插入等函数。
函数不做类外定义,也不分文件定义,写得也比较紧凑,同样都是为了节约篇幅。o(╯╰)o

#include 
using namespace std;

typedef int ElementType;
typedef struct node INode;
struct node {
    ElementType data;
    INode *next;
};
 
template 
class List {
public:
    List() {    //创建一个头结点。 
 pList = new Node;
 pList->next = NULL;
 len = 0;
    }
    ~List() {
 clearList();
 delete pList;
    }
    void clearList() {
 Node *currNode = pList->next;
 while (currNode != NULL) {
     Node *tmp = currNode->next;
     delete currNode;
     currNode = tmp;
 }
 len = 0;
    }
    int listLen() const { return len; }
    bool getElem(int i, ElementType &elem) {
 if (i < 0  i >= len) return false;
 Node *iNode = iNodePointer(i)->next;
 elem = iNode->data;
 return true;
    }
    
    Node* iNodePointer(int index) {
 Node *iNode = pList;
 for (int i = 0; i < index; i++)
     iNode = iNode->next;
 return iNode;
    }
    int locateElem(const ElementType &elem) {
 Node *tmp = pList;
 for (int i = 0; i < len; i++) {
     tmp = tmp->next;
     if (tmp->data == elem) return i;
 }
 return -1;
    }
    //在第i个位置插入elem,i从0开始,i=len表示插在链表尾部。 
    bool insertList(int i, const ElementType &elem) {
 if (i < 0  i > len) return false;
 Node *newNode = new Node;
 newNode->data = elem;
 Node *iNode = iNodePointer(i);
 newNode->next = iNode->next;
 iNode->next = newNode;
 len++;
 return true;
    }
    bool deleteList(int i, ElementType &elem) {
 if (i < 0  i >= len) return false;
 Node *iNode = iNodePointer(i);
 Node *deNode = iNode->next;
 elem = deNode->data;
 iNode->next = deNode->next;
 delete deNode;
 len--;
 return true;
    }
    void traverseList() {
 Node *tmp = pList->next;
 while (tmp != NULL) {
     cout << tmp->data << endl;
     tmp = tmp->next;
 }
    }
private:
    Node *pList;
    int len;
};

int main(void) {
    List *ls = new List;
    ls->insertList(ls->listLen(), 1);
    ls->insertList(ls->listLen(), 2);
    ls->insertList(ls->listLen(), 3);
    ls->insertList(1, 4);
    ls->traverseList();
    ElementType tmp;
    ls->getElem(1, tmp);
    cout << "tmp = " << tmp << endl;
    ls->deleteList(2, tmp);
    cout << "tmp = " << tmp << endl;
    ls->traverseList();

    delete ls;
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/233091.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号