鏈表輸入與輸出

/********
6 11
1 4 4 
1 2 3
2 5 4
2 4 2
2 3 3
2 1 5
4 5 4
4 1 2
5 6 5
5 2 6
6 3 4
********/ 
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
const int MaxNum = 1005; 
//邊集 
struct edge{
    int from,to,w; //起點,終點 ,權重 
};
//鄰接點
struct node{
    int idx;//鄰接點下標
    int w;//邊權重
    node* next;//下一個鄰接點的指針 
}; 
//鄰接表
struct vnode{
    node *first; //邊表的頭指針,每個點的第一條邊的指針
    int data; //點編號 
}; 
struct graph{
    int nVertex; //頂點數 
    int mEdge; //邊數
    vnode adjlist[MaxNum]; //鄰接表 
}; 
//根據點的數量n初始化圖
graph* initGraph(int n,int m);
//加邊 
void insertEdge(graph* g,edge e);
//建圖
graph* buildGraph();
//打印圖
void printGraph(graph*);
//打印鄰接點 
void printlist(node* head);
int main(){
    graph *g = buildGraph();
    printGraph(g);
    return 0;
}
//根據點的數量n初始化圖
graph* initGraph(int n,int m){
    graph *g = new graph();//(graph*)malloc(sizeof(graph))
    g->nVertex = n;
    g->mEdge = m;
    for(int i = 1;i<=n;i++){
        g->adjlist[i].data = i;//點的數據默認編號
        g->adjlist[i].first = NULL; //默認沒有邊 
    }
    return g;
}
//建圖
graph* buildGraph(){
    int n,m;
    scanf("%d%d",&n,&m);    //讀入點數和邊數 
    graph *g = initGraph(n,m);//初始化圖 
    //加邊
     while(m--){
         edge te;    //定義一條邊 
         scanf("%d%d%d",&te.from,&te.to,&te.w); 
         insertEdge(g,te);
    }
    return g;
}
//加邊 
void insertEdge(graph* g,edge e){
    //插入邊<e.from,e.to>
    node *p = new node();//創建一個新否鄰接點 
    p->idx = e.to;        //終點 
    p->w = e.w;            //權重 
    p->next = g->adjlist[e.from].first;
    g->adjlist[e.from].first = p;
    //無向圖,還需要在增加一個鄰接表 
} 

void printGraph(graph* g){
    for(int i = 1;i <= g->nVertex;i++){
        printf("%d ",i);                    //打印定點數據 
        printlist(g->adjlist[i].first);//打印每個頂點的鄰接表 
    } 
}
//打印鄰接點 
void printlist(node* head){
    if(head == NULL){
        printf("\n");
        return;
    }    
    node *p = head;
    while(p != NULL){
        printf("-> %d ",p->idx);
        p = p->next;
    } 
    printf("\n"); 
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章