图的邻接列表表示法
writer:pprp
今天学的是邻接列表表示法
邻接列表表示法是用链表来记录各顶点的邻接顶点;
其节点结构为: 邻接顶点->下一邻接顶点->下一邻接顶点...
#include <iostream> using namespace std; const int N = 6; struct node { int vertex; node*next; }; node head[N]; void create(int node1,int node2)//通过起点和终点的值创建一个邻接表 { node * point; node * New = new node(); if(New!=NULL) { New->vertex = node2; New->next = NULL; point = &(head[node1]); while(point->next!=NULL)//注意这个地方应该是point->next而不是point,否则会越界 point = point->next; point->next = New; } } void print() { node*point; for(int i = 0; i < N; i++) { point = head[i].next; cout << "Head["<<i<<"]"; while(point!=NULL) { cout <<"-> "<<point->vertex; point = point->next; } cout << endl; } } int main() { int node1,node2; for(int i = 0; i < N;i++) { head[i].vertex = i; head[i].next = NULL; } while(1) { cout <<"please enter the start point" << endl; cin >> node1; if(node1 == -1) break; cout <<"please enter the end point" << endl; cin >> node2; if(node1 == node2) cout <<"自身循环"<<endl; else if(node1>=N||node2>=N) cout <<"超出范围"<<endl; else create(node1,node2); } cout << "邻接表为:" << endl; print(); return 0; }
代码改变世界