【发布时间】:2016-10-15 11:24:09
【问题描述】:
我正在尝试通过一组单链表创建邻接表。
查看我的代码。
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct city
{
int id;
struct city *next;
}city;
int main()
{
int num_city, index = 0, length;
cin >> num_city;
length = num_city;
city **adj_list = new city*[num_city]; // here it's the header node
for(int index = 0 ; index < length ; index++)
adj_list[index] = new city;
city **temp = adj_list;
while( num_city -- )
{
int a,b;
cin >> a;
cin >> b;
a--;
b--;
city *t1 = new city;
t1 -> id = a;
t1 -> next = NULL;
city *t2 = new city;
t2 -> id = b;
t2 -> next = NULL;
temp[a] -> next = t2;
temp[b] -> next = t1;
temp[a] = temp[a] -> next;
temp[b] = temp[b] -> next;
}
for ( int index = 0; index < length ; index ++)
delete [] adj_list[index];
delete [] adj_list;
adj_list = NULL;
exit(0);
}
当我试图逐个遍历单链表时,它的输出是NULL。
在GDB这段代码之后,我发现:开始循环,city创建成功,adj_list[index]也可以指向正确的内存位置。一旦进入下一个循环,adj_list[index] 就会意外地等于NULL。
怎么了?
【问题讨论】:
标签: c++ arrays singly-linked-list adjacency-list