图的邻接表存储 c实现

#include <iostream>
using namespace std;

int n;
int e;
typedef struct node{
    int element;
    node*next;
}Edge;

typedef  Edge* AdjGraph;
AdjGraph G;

void Create(int maxedge){
    G = (AdjGraph)malloc(sizeof(Edge)*(maxedge+5));
    n=maxedge;
    e=0;
    for(int i = 1 ; i <= maxedge ; i++) {
        G[i].next=NULL;
        G[i].element=i;
    }
}

void addEdge(int p,int q){
    e++;
    Edge* new1=(Edge*)malloc(sizeof(Edge));
    new1->next=G[p].next;
    new1->element=q;
    G[p].next=new1;
    if(p==q) return ;//防止p==q的时候增加两次

    Edge* new2=(Edge*)malloc(sizeof(Edge));
    new2->next=G[q].next;
    new2->element=p;
    G[q].next=new2;
}

void print(){
    for(int i = 1;i<=n;i++){
        cout<<"i=="<<i<<endl;
        Edge* current=G[i].next;
        while(current!=NULL){
            cout<<current->element<<",";
            current=current->next;
        }
        cout<<endl;
    }
}

int main(){
    Create(5);
    addEdge(1,2);
    addEdge(2,3);
    addEdge(5,2);
    addEdge(2,2);
    cout<<"edges="<<e<<endl;
    print();
    return 0;
}

你可能感兴趣的:(图的邻接表存储 c实现)