C/C++ 一个简单的链表

好久没搞C了….都忘得差不多了

重新来碰C,想写个socket,都忘光了,然后去自己博客找,还找到了自己原来写的一个demo= =

用昨天晚自习的时间,学习了下,写了个简单的链表

[cpp]
// study.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
template<class T>

class chainlist {
private:
T m_pData;
chainlist* m_pHead;
chainlist* m_pNext;
public:
chainlist* getheadchain() {
return m_pHead;
}
T getdata(int pos) {//获取
chainlist* tmp=m_pHead;
for (int i = 0; pos > i; i++) {
if (tmp->m_pNext == NULL) {
tmp = NULL;
break;
}
tmp = tmp->m_pNext;
}
return tmp->m_pData;
}
chainlist* adddata(T data) {//添加
m_pNext = new chainlist;
m_pNext->m_pData = data;
m_pNext->m_pHead = m_pHead;
return m_pNext;
}
chainlist() {//构造函数
m_pHead = this;
m_pNext = NULL;
}
chainlist* insertdata(T data,int pos) {//插入
chainlist* tmp = m_pHead;
chainlist* t = new chainlist;
for (int i=0; true;i++) {
if (i == pos) {
t->m_pData = data;
t-> m_pHead = m_pHead;
t->m_pNext = tmp->m_pNext;
tmp->m_pNext = t;
return t;
}
if (tmp->m_pNext == NULL) {
tmp = NULL;
break;
}
tmp = tmp->m_pNext;
}
delete t;
return NULL;
}
bool deletedata(int pos) {//删除
chainlist* tmp = m_pHead;
for (int i = 0; true; i++) {
if (i == pos-1) {
chainlist* t = tmp->m_pNext;
tmp->m_pNext = tmp->m_pNext->m_pNext;
delete t;
return true;
}
if (tmp->m_pNext == NULL){
break;
}
tmp = tmp->m_pNext;
}
return false;
}
static chainlist* deletealldata(chainlist* head) {//删除所有
chainlist* tmp = head->m_pNext;
head->m_pNext = NULL;
if (tmp == NULL)
return head;
for (int i = 0; true;i++) {
if (tmp->m_pNext == NULL) {
break;
}
chainlist* t=tmp;
tmp = tmp->m_pNext;
delete t;
}
return head;
}
chainlist* gethead() {//获取头
return m_pHead;
}
~chainlist() {

}
};
int main()
{
chainlist<int>* chain=new chainlist<int>;
for (int a = 0; a < 5; a++) {
int b;
scanf_s("%d", &b);
chain=chain->adddata(b);
}
chain->insertdata(4,1);
printf("%d", chain->getdata(2));
chain->deletedata(2);
chain = chain->getheadchain();
chain = chain->gethead();
chainlist<int>::deletealldata(chain);
return 0;
}
[/cpp]

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据