原贴地址:http://blog.csdn.net/feixiaoxing/article/details/6922766
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
前面我们讨论过图的基本结构是什么样的。它可以是矩阵类型的、数组类型的,当然也可以使指针类型的。当然,就我个人而言,比较习惯使用的结构还是链表指针类型的。本质上,一幅图就是由很多节点构成的,每一个节点上面有很多的分支,仅此而已。为此,我们又对原来的结构做了小的改变:
- typedef struct _LINE
- {
- int end;
- int weight;
- struct _LINE* next;
- }LINE;
- typedef struct _VECTEX
- {
- int start;
- int number;
- LINE* neighbor;
- struct _VECTEX* next;
- }VECTEX;
- typedef struct _GRAPH
- {
- int count;
- VECTEX* head;
- }GRAPH;
- VECTEX* create_new_vectex(int start)
- {
- VECTEX* pVextex = (VECTEX*)malloc(sizeof(VECTEX));
- assert(NULL != pVextex);
- pVextex->start = start;
- pVextex->number = 0;
- pVextex->neighbor = NULL;
- pVextex->next = NULL;
- return pVextex;
- }
- LINE* create_new_line(int end, int weight)
- {
- LINE* pLine = (LINE*)malloc(sizeof(LINE));
- assert(NULL != pLine);
- pLine->end = end;
- pLine->weight = weight;
- pLine->next = NULL;
- return pLine;
- }
- VECTEX* create_new_vectex_for_graph(int start, int end, int weight)
- {
- VECTEX* pVectex = create_new_vectex(start);
- assert(NULL != pVectex);
- pVectex->neighbor = create_new_line(end, weight);
- assert(NULL != pVectex->neighbor);
- return pVectex;
- }
- GRAPH* create_new_graph(int start, int end, int weight)
- {
- GRAPH* pGraph = (GRAPH*)malloc(sizeof(GRAPH));
- assert(NULL != pGraph);
- pGraph->count = 1;
- pGraph->head = create_new_vectex_for_graph(start, end, weight);
- assert(NULL != pGraph->head);
- return pGraph;
- }
- VECTEX* find_vectex_in_graph(VECTEX* pVectex, int start)
- {
- if(NULL == pVectex)
- return NULL;
- while(pVectex){
- if(start == pVectex->start)
- return pVectex;
- pVectex = pVectex->next;
- }
- return NULL;
- }
- LINE* find_line_in_graph(LINE* pLine, int end)
- {
- if(NULL == pLine)
- return NULL;
- while(pLine){
- if(end == pLine->end)
- return pLine;
- pLine = pLine->next;
- }
- return NULL;
- }
总结:
(1)图就是多个链表的聚合
(2)想学好图,最好把前面的链表和指针搞清楚、弄扎实
(3)尽量写小函数,小函数构建大函数,方便阅读和调试