C++源码:封装一个简单的模板链表,自定义类型数据小小测试一下

1.创建存储数据,重载运算符

C++源码:封装一个简单的模板链表,自定义类型数据小小测试一下

更多源码:747821062

2.链表的结点结构体

C++源码:封装一个简单的模板链表,自定义类型数据小小测试一下

3.C++封装List

C++源码:封装一个简单的模板链表,自定义类型数据小小测试一下

4.主函数测试

C++源码:封装一个简单的模板链表,自定义类型数据小小测试一下

更多源码:747821062

5.结果展示

C++源码:封装一个简单的模板链表,自定义类型数据小小测试一下

完整源码:

#include <iostream>

#include <string>

#include <cstring>

using namespace std;

struct Info{

char name[20];

int age;

int num;

};

ostream& operator<

{

out << data.name << "\t" << data.age << "\t" << data.num;

return out;

}

template <typename>

void print(T data)

{

cout << data << endl;

}

template <typename>

struct Node

{

T data;

Node* next;

Node(T data) :data(data)

{

this->next = NULL;

}

Node(T data, Node* next)

{

this->data = data;

this->next = next;

}

};

template <typename>

class List

{

public:

List()

{

firstNode = NULL;

}

void insertNodeByHead(T data)

{

//无表头表头法插入

firstNode = new Node(data, firstNode);

}

void deleteNodeByAppoin(const char *name)

{

Node* pMove = firstNode;

Node* pMoveNext = firstNode->next;

if (!strcmp(pMove->data.name, name))

{

Node* nextNode = firstNode->next;

delete firstNode;

firstNode = nextNode;

}

else

{

while (pMoveNext != NULL&&strcmp(pMoveNext->data.name, name))

{

pMove = pMoveNext;

pMoveNext = pMove->next;

}

if (pMoveNext == NULL)

{

cout << "未找到要删除的点" << endl;

return;

}

else

{

pMove->next=pMoveNext->next;

delete pMoveNext;

pMoveNext = NULL;

}

}

}

void printList()

{

Node* pMove = firstNode;

while (pMove)

{

cout << pMove->data << endl;

pMove = pMove->next;

}

cout << endl;

}

~List()

{

while (firstNode)

{

Node* nextNode = firstNode->next;

delete firstNode;

firstNode = nextNode;

}

}

protected:

Node* firstNode;

};

int main()

{

Info myInfo = { "Joker", 29, 1 };

print(myInfo);

List *pList = new List;

pList->insertNodeByHead(1);

pList->insertNodeByHead(2);

pList->printList();

List<info> *pJoker = new List<info>;/<info>/<info>

pJoker->insertNodeByHead(myInfo);

Info info = { "醉七年", 39, 2 };

pJoker->insertNodeByHead(info);

pJoker->printList();

pJoker->deleteNodeByAppoin(myInfo.name);

pJoker->printList();

system("pause");

return 0;

}


分享到:


相關文章: