图的数据结构实现

  1 #include"iostream"
  2 #include"malloc.h" 
  3 #include"queue"
  4 using namespace std;
  5 #define MAX 50
  6 typedef struct node{
  7     int adjvex;    //拎接点域 
  8     struct node *next; //链域 
  9     int weight;
 10 }EdgeNode;
 11 typedef struct vnode{
 12     int vertex;        //顶点域 
 13     EdgeNode *firstedge;//边表头指针 
 14 }VertexNode;
 15  typedef VertexNode AdjList[MAX];
 16  
 17  typedef struct{
 18      AdjList adjlist;//邻接表     
 19      int n;
 20     int e;
 21                //图中当前顶点和边数 
 22  }AlGraph;
 23  //建立图的邻接表 
 24  void CreatAlGraph(AlGraph *G){
 25      EdgeNode *s;        //定义边表节点
 26      int i,j,k;
 27      int a;
 28      cout<<"请输入顶点边和边数"<<endl;
 29      cin>>i>>j;
 30      G->n=i;
 31      G->e=j;
 32      cout<<"请输入顶点编号"<<endl;
 33      for(i=0;i<G->n;i++){
 34          cin>>a;
 35          G->adjlist[i].vertex=a;
 36         G->adjlist[i].firstedge=NULL; 
 37      } 
 38      cout<<"请输入由两个顶点构成的边,"<<endl;
 39      for(k=0;k<G->e;k++){
 40          cin>>i>>j;
 41          s=(EdgeNode*)malloc(sizeof(EdgeNode));
 42          s->adjvex=j;
 43          s->next=G->adjlist[i].firstedge;
 44          G->adjlist[i].firstedge=s;//将新节点s插入顶点BI的边表头部
 45         /*若建立无向图,则添加下面的代码*/
 46         s=(EdgeNode*)malloc(sizeof(EdgeNode));
 47         s->adjvex=i;
 48         s->next=G->adjlist[j].firstedge;
 49         G->adjlist[j].firstedge=s;      
 50      }
 51  }
 52  //深度优先算法 
 53  bool visited[MAX];
 54  void DFS(AlGraph *G,int i){//以VI为出发点对邻接表的进行DFS 
 55      EdgeNode *p;
 56      cout<<G->adjlist[i].vertex;
 57      visited[i]=true;
 58      p=G->adjlist[i].firstedge;
 59      while(p){
 60          if(!visited[p->adjvex])
 61              DFS(G,p->adjvex);
 62          p=p->next;
 63      }
 64  }
 65   void DepthFirstsearch(AlGraph *G,int v){
 66      for(int i=0;i<G->n;i++)    
 67          visited[i]=false;
 68      DFS(G,v);
 69  }
 70  void BFS(AlGraph *G,int v){
 71      EdgeNode *p;
 72      queue<int>Q;
 73      visited[v]=true;
 74      Q.push(v);
 75      while(!Q.empty()){
 76          int v=Q.front();
 77          cout<<v;
 78          Q.pop();
 79          p=G->adjlist[v].firstedge;
 80          while(p){
 81              if(!visited[p->adjvex]){ 
 82                  visited[p->adjvex]=true;
 83                  Q.push(p->adjvex);
 84             } 
 85             p=p->next;
 86          }
 87      }
 88  }
 89  void BFSEARCH(AlGraph *G,int v){
 90      for(int i=0;i<G->n;i++)    
 91          visited[i]=false;
 92      BFS(G,v);
 93  }
 94  int main(){
 95      AlGraph *G=(AlGraph*)malloc(sizeof(AlGraph));
 96     CreatAlGraph(G);
 97      DepthFirstsearch(G,0);
 98      cout<<endl;
 99      BFSEARCH(G,0);
100      return 0;
101  }

 

posted @ 2016-04-22 00:25  Hutonm  阅读(266)  评论(0编辑  收藏  举报