现在的位置: 首页 > 综合 > 正文

创建图结构

2014年02月15日 ⁄ 综合 ⁄ 共 2416字 ⁄ 字号 评论关闭

本文紧接上一篇文章:图结构入门

前面我们讨论过图的基本结构是什么样的。它可以是矩阵类型的、数组类型的,当然也可以使指针类型的。当然,就我个人而言,比较习惯使用的结构还是链表指针类型的。本质上,一幅图就是由很多节点构成的,每一个节点上面有很多的分支,仅此而已。为此,我们又对原来的结构做了小的改变:

  1. typedef struct _LINE  
  2. {  
  3.     int end;  
  4.     int weight;  
  5.     struct _LINE* next;  
  6. }LINE;  
  7.   
  8. typedef struct _VECTEX  
  9. {  
  10.     int start;  
  11.     int number;  
  12.     LINE* neighbor;  
  13.     struct _VECTEX* next;  
  14. }VECTEX;  
  15.   
  16. typedef struct _GRAPH  
  17. {  
  18.     int count;  
  19.     VECTEX* head;  
  20. }GRAPH;  

    为了创建图,首先我们需要创建节点和创建边。不妨从创建节点开始,

  1. VECTEX* create_new_vectex(int start)  
  2. {  
  3.     VECTEX* pVextex = (VECTEX*)malloc(sizeof(VECTEX));  
  4.     assert(NULL != pVextex);  
  5.   
  6.     pVextex->start = start;  
  7.     pVextex->number = 0;  
  8.     pVextex->neighbor = NULL;  
  9.     pVextex->next = NULL;  
  10.     return pVextex;  
  11. }  

    接着应该创建边了,

  1. LINE* create_new_line(int end, int weight)  
  2. {  
  3.     LINE* pLine = (LINE*)malloc(sizeof(LINE));  
  4.     assert(NULL != pLine);  
  5.       
  6.     pLine->end = end;  
  7.     pLine->weight = weight;  
  8.     pLine->next = NULL;  
  9.     return pLine;  
  10. }  

    有了上面的内容,那么创建一个带有边的顶点就变得很简单了,

  1. VECTEX* create_new_vectex_for_graph(int start, int end, int weight)  
  2. {  
  3.     VECTEX* pVectex = create_new_vectex(start);  
  4.     assert(NULL != pVectex);  
  5.       
  6.     pVectex->neighbor = create_new_line(end, weight);  
  7.     assert(NULL != pVectex->neighbor);  
  8.       
  9.     return pVectex;  
  10. }  

    那么,怎么它怎么和graph相关呢?其实也不难。

  1. GRAPH* create_new_graph(int start, int end, int weight)  
  2. {  
  3.     GRAPH* pGraph = (GRAPH*)malloc(sizeof(GRAPH));  
  4.     assert(NULL != pGraph);  
  5.   
  6.     pGraph->count = 1;  
  7.     pGraph->head = create_new_vectex_for_graph(start, end, weight);  
  8.     assert(NULL != pGraph->head);  
  9.   
  10.     return pGraph;  
  11. }  

    有了,有了,那么节点和边的查找也不难了。

  1. VECTEX* find_vectex_in_graph(VECTEX* pVectex, int start)  
  2. {  
  3.     if(NULL == pVectex)  
  4.         return NULL;  
  5.   
  6.     while(pVectex){  
  7.         if(start == pVectex->start)  
  8.             return pVectex;  
  9.         pVectex = pVectex->next;  
  10.     }  
  11.   
  12.     return NULL;  
  13. }  
  14.   
  15. LINE* find_line_in_graph(LINE* pLine, int end)  
  16. {  
  17.     if(NULL == pLine)  
  18.         return NULL;  
  19.   
  20.     while(pLine){  
  21.         if(end == pLine->end)  
  22.             return pLine;  
  23.   
  24.         pLine = pLine->next;  
  25.     }  
  26.   
  27.     return NULL;  
  28. }  

总结:

    (1)图就是多个链表的聚合

    (2)想学好图,最好把前面的链表和指针搞清楚、弄扎实

    (3)尽量写小函数,小函数构建大函数,方便阅读和调试

转载请注明:http://blog.csdn.net/shanzhizi

来自:http://blog.csdn.net/feixiaoxing/article/details/6922766

抱歉!评论已关闭.