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

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

#include <iostream>
using namespace std;

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

template <typename T>
{
public:

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

protected:
int m_len;
};

template <typename T>
{
m_len = 0;
}

template <typename T>
{
Node<T> *tmp = NULL;

{
}
}

template <typename T>
{
//把旧的结点 del掉
Node<T> *tmp = NULL;
{
}
//重新创建
m_len = 0;
return 0;
}
template <typename T>
{
Node<T> *current = NULL;

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>
{
Node<T> *current = NULL;

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

template <typename T>
{
Node<T> *current = NULL;
Node<T> *ret = NULL;

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>
{
return m_len;
}

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

#include <iostream>
using namespace std;

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

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

//插入元素
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 ;
}

09-27 453
06-15 1471

10-08 54
09-20 7903
02-24 4万+
10-17 5498
12-18 1万+
04-18 2万+
06-13 1万+
01-21 3324
04-04 4019
07-28 1万+
02-19 1万+
01-19 5052
06-11 2万+
03-26 1万+
07-13 1万+
07-22 3万+
11-28 5586