指针实现邻接表模板
自己写的一个无向图邻接表,edge代表邻接的节点,head代表邻接表主体节点。
不是很喜欢用数组建表,主要是因为数组建表虽然实现简单,但是理解略显复杂,这个方面可以参考朝夕的博客。
struct edge
{
edge *next;
int num;
int len;
};
edge eg[100000];
struct head
{
edge *next;
int num;
};
head h[100000];
void IniList(int n)
{
int i;
for (i = 1; i <= n; i++)
{
h[i].next = NULL;
h[i].num = i;
}
}
void CreatList(int n, int m)
{
int i;
int x, y, leng;
for (i = 0; i < m; i++)
{
cin >> x >> y >> leng;
edge *p1, *p2;
p1 = new edge;
p1 -> next = NULL;
p1 -> num = y;
p1 -> len = leng;
p2 = new edge;
p2 -> next = NULL;
p2 -> num = x;
p2 -> len = leng;
edge *p3, *p4;
p3 = h[x].next;
if (p3 == NULL) {
h[x].next = p1;
}
else
{
while (p3 -> next != NULL) {
p3 = p3 -> next;
}
p3 -> next = p1;
}
p4 = h[y].next;
if (p4 == NULL) {
h[y].next = p2;
}
else
{
while (p4 -> next != NULL) {
p4 = p4 -> next;
}
p4 -> next = p2;
}
}
}
void PrintList(int n)
{
int i;
edge *p;
for (i = 1; i <= n; i++)
{
p = h[i].next;
cout << "Node:" << h[i].num << endl;
while (p != NULL) {
cout << p -> num << " " << p -> len << " ";
p = p -> next;
}
cout << endl;
}
}
上面的CreatList是在函数内部输入,并且是为无向图服务的(分别在h[x]和h[y]都增加了节点),如果是无向图的话也可以在外部调用两次下面的函数:CreatList(x, y, leng); CreatList(y, x, leng);
void CreatList(int x, int y, int leng)
{
edge *p1, *p2;
p1 = new edge;
p1 -> next = NULL;
p1 -> num = y;
p1 -> len = leng;
p2 = h[x].next;
if (p2 == NULL) {
h[x].next = p1;
}
else
{
while (p2 -> next != NULL) {
p2 = p2 -> next;
}
p2 -> next = p1;
}
}
2016/12/18
To improve is to change, to be perfect is to change often.