数据结构与算法学习--邻接表

来源:互联网 发布:excel数据区域设置 编辑:程序博客网 时间:2024/05/20 05:08

众所周知,图的存储方式有两种,一种是领接矩阵(即二维数组),还有一种是领接表。
领接矩阵适合于稠密图,领接表适用于稀疏图(点多边少)。
领接表即给图中每个顶点创建一个单链表,第i个单链表中的结点表示依附于顶点Vi的边,每个单链表的头节点形成一个一维数组,以便于顶点的访问。具体代码如下:

#include <iostream>using namespace std;#include <malloc.h>typedef struct node //定义用来存图中每个结点的结构体指针{    int data;    struct node *next;}Node, *next_node;void insert(next_node Head[], int data, int nums) //给每个结点插入边{    next_node temp = (next_node)malloc(sizeof(Node));    temp->data = data;    temp->next = Head[nums];    Head[nums] = temp;} void output(next_node Head[], int len) //输出每个结点所连接的边{    for(int i = 0; i < len; i++)    {        next_node temp = Head[i];        cout<<i<<"->";        while(temp != NULL)        {            cout<<temp->data<<" ";            temp = temp->next;        }           cout<<endl;    }       }int main(){    int n, m;    int x, y;    cin>>n;    next_node *Head = (next_node*)malloc(sizeof(Node)*n);    memset(Head, 0, sizeof(Head)*n);    for(int i = 0; i < n; i++)    {        cin>>x>>y;        insert(Head, y, x);    }    output(Head, n);    return 0;}
0 0
原创粉丝点击