1.创建存储数据,重载运算符
2.链表的结点结构体
3.C++封装List
4.主函数测试
5.结果展示
完整源码:
#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
Node(T data) :data(data)
{
this->next = NULL;
}
Node(T data, Node
{
this->data = data;
this->next = next;
}
};
template <typename>
class List
{
public:
List()
{
firstNode = NULL;
}
void insertNodeByHead(T data)
{
//无表头表头法插入
firstNode = new Node
}
void deleteNodeByAppoin(const char *name)
{
Node
Node
if (!strcmp(pMove->data.name, name))
{
Node
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
while (pMove)
{
cout << pMove->data << endl;
pMove = pMove->next;
}
cout << endl;
}
~List()
{
while (firstNode)
{
Node
delete firstNode;
firstNode = nextNode;
}
}
protected:
Node
};
int main()
{
Info myInfo = { "Joker", 29, 1 };
print(myInfo);
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;
}
閱讀更多 C語言基礎 的文章