Code:
- // 链树.cpp : 定义控制台应用程序的入口点。
- #include “stdafx.h”
- #include <iomanip>//
- #include <iostream>
- using namespace std;
- #define MAX_VERTEX 10
- typedef struct Node
- {int vertex;
- struct Node *next;
- }node,*Pnode;
- typedef struct Node adjlist[MAX_VERTEX];
- void Creat_Graph(adjlist G,int &n)
- {int e,s,d;
- Pnode p,q;
- cout<<“input vertex num & edge num”<<endl;
- cin>>n>>e;
- for(int i=0;i<n;i++)
- {G[i].vertex=i;
- G[i].next=NULL;
- }
- for(int i=0;i<e;i++)//
- {cout<<“input the “<<i<<” edge’s two vertex”
- <<endl;
- cin>>s
- >>d;
- p=new node;
- p->vertex=d;
- p->next=NULL;
- q=&G[s];
- while(q->next)q=q->next;
- q->next=p;
- //no directed
- p=new node;
- p->vertex=s;
- p->next=NULL;
- q=&G[d];
- while(q->next)q=q->next;
- q->next=p;
- //
- }
- }
- void Print_Graph(adjlist G,int n)
- {Pnode p;
- for(int i=0;i<n;i++)
- {cout<<G[i].vertex;
- p=G[i].next;
- while(p!=NULL)
- {
- cout<<“→”<<p->vertex;
- p=p->next;
- }
- cout<<endl;
- }
- }
- /*****************deep******************/
- int visited[MAX_VERTEX];
- void Depth_First_Search(adjlist G,int v)
- {
- Pnode p;
- visited[v]=1;
- cout<<setw(3)<<v;
- p=G[v].next;
- while(p)
- {if(visited[p->vertex]==0)
- {
- Depth_First_Search(G,p->vertex);
- }
- p=p->next;
- }
- cout<<endl;
- }
- int visited2[MAX_VERTEX];
- int queue[MAX_VERTEX];
- void Breadth_First_Search(adjlist G,int vi)
- {int front=0,rear=0,v;
- Pnode p;
- visited2[vi]=1;cout<<setw(3)<<vi;//visit
- queue[rear]=vi;rear++;//input
- while(front!=rear)
- {v=queue[front];front++;//delete
- p=G[v].next;
- while(p)
- {
- if(visited2[p->vertex]==0)
- {
- visited2[p->vertex]=1;cout<<setw(3)<<p->vertex;
- queue[rear]=p->vertex;rear++;//input
- }
- p=p->next;
- }//while p
- }
- }
- int main()
- {
- int n;
- adjlist G;
- Creat_Graph(G,n);
- Print_Graph(G,n);
- cout << “Hello world!” << endl;
- Depth_First_Search(G,0);
- Breadth_First_Search(G,0);
- int t;
- cin>>t;
- return 0;
- }