数据结构与算法--链表C++实现

=================================================================

linklist.h

#include <iostream>
using namespace std;


template <typename T>
struct Node
{
T t; //
struct Node<T> *next;
};


template <typename T>
class LinkList
{
public:
LinkList();
~LinkList();

public:
int clear();
int insert(T &t, int pos);
int get(int pos, T &t);
int del(int pos, T &t);
int getLen();

protected:
Node<T> *m_header;
int m_len;
};

template <typename T>
LinkList<T>::LinkList()
{
m_header = new Node<T>;
m_header->next = NULL;
m_len = 0;
}

template <typename T>
LinkList<T>::~LinkList()
{
Node<T> *tmp = NULL;

while (m_header !=NULL)
{
tmp = m_header->next;
delete m_header;
m_header = tmp;
}
}

template <typename T>
int LinkList<T>::clear()
{
//把旧的结点 del掉
Node<T> *tmp = NULL;
while (m_header)
{
tmp = m_header->next;
delete m_header;
m_header = tmp;
}
//重新创建
m_header = new Node<T>;
m_len = 0;
return 0;
}
template <typename T>
int LinkList<T>::insert(T &t, int pos)
{
Node<T> *current = NULL;


current = m_header;

for (int i=0; i<pos; i++)
{
current = current->next;
}

//把上层应用的t结点 缓存到容器中

Node<T> *node = new Node<T>;
node->next = NULL;
node->t = t; // 把t1缓存下来

//把node结点 在pos位置 加入到链表中

node->next = current->next;
current->next = node;

m_len ++;
return 0;
}

template <typename T>
int LinkList<T>::get(int pos, T &t)
{
Node<T> *current = NULL;

current = m_header;

for (int i=0; i<pos; i++)
{
current = current->next;
}
t = current->next->t;
return 0;
}

template <typename T>
int LinkList<T>::del(int pos, T &t)
{
Node<T> *current = NULL;
Node<T> *ret = NULL;

current = m_header;

for (int i=0; i<pos; i++)
{
current = current->next;
}
ret = current->next;
t = ret->t; //把缓存的结点 给上层应用t

//删除操作
current->next = ret->next; 
m_len --;
delete ret; //注意释放内存  因为insert的时候 new Node<T>

return 0;
}

template <typename T>
int LinkList<T>::getLen()
{
return m_len;
}


===========================================================

链表类测试框架.cpp


#include <iostream>
using namespace std;


#include "LinkList.h"

struct Teacher
{
char name[32];
int age;
};

void main01()
{
Teacher t1, t2, t3;
Teacher  tmp;
t1.age = 31;
t2.age = 32;
t3.age = 33;


LinkList<Teacher> list;

//插入元素 
list.insert(t1, 0);
list.insert(t2, 0);
list.insert(t3, 0);

//遍历链表

for (int i=0; i<list.getLen(); i++)
{
list.get(i, tmp);
printf("age:%d ", tmp.age);
}

//销毁链表
while (list.getLen() > 0)
{
list.del(0, tmp);
printf("age:%d ", tmp.age);
}
}

void main()
{
main01();
cout<<"hello..."<<endl;
system("pause");
return ;
}






















已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页