type
Post
status
Invisible
date
Sep 1, 2016
slug
summary
临街表介绍
tags
数据结构
算法
category
技术分享
icon
password
URL
C语言构建邻接表
notion image
 

背景

折腾

学校oj上DFS题只要求写搜索部分,而且创建邻接表的函数高大上一时间看不明白,写这个算是练练手吧,加深对邻接表的理解。

邻接矩阵 VS 邻接表

邻接矩阵
邻接表
相对优点
建图简单粗暴
空间复杂度小
相对缺点
空间复杂度高
判重比较麻烦

邻接矩阵

数据结构图

Edge
a
b
c
...
n
a
b
c
...
n

代码实现

int array[10][10] = {0}; void cteate_array() {    char x;    char y;    for (int k = 0; k < edge; k++) {        fflush(stdin);        scanf("%c %c", &x, &y);        array[x - 'a'][y - 'a'] = 1;   } }
input
output
1
2
3
0
a
b
3 3
a
1
a b c
b
a b
c
1
b c
c b

传统创建邻接表

数据结构图

notion image

代码实现

#include <iostream> #include "stdio.h" #include "string.h" #include "stdlib.h" using namespace std; typedef char vertex_type[20]; int num; int edge; int kind; // kind = 0 : 有向图 // kind = 1 : 无向图 typedef struct arcnode {    int cur;    struct arcnode *next; } arcnode, *arcnode_p; typedef struct vnode {    vertex_type data;    struct arcnode *first; } vnode, *nodelist; // 输入data,返回邻接表的cur int getnode(vnode *G, char *data) {    int i;    for (i = 0; i < num; i++)        if (strcmp(data, G[i].data) == 0)            return i;    return -1; } void create(vnode *G, int kind) {    for (int i = 0; i < num; i++) {        scanf("%s", G[i].data);        G[i].first = NULL;   }    int po;    int nex;    for (int i = 0; i < edge; i++) {        char a[20] = {'\0'};        char b[20] = {'\0'};        scanf("%s%s", a, b);        if ((po = getnode(G, a)) >= 0 && (nex = getnode(G, b)) >= 0) {            arcnode_p new_node;            // 新建结点            new_node = new arcnode;            new_node->cur = nex;            new_node->next = NULL;            // 如果头为空,直接链到first            if (G[po].first == NULL)                G[po].first = new_node;            else {                arcnode_p p;                p = G[po].first;                while (p->next != NULL) {                    p = p->next;               }                p->next = new_node;           }            // 如果是无序图            if (kind == 1) {                // 新建结点                new_node = new arcnode;                new_node->cur = po;                new_node->next = NULL;                // 如果头为空,直接链到first                if (G[nex].first == NULL)                    G[nex].first = new_node;                else {                    arcnode_p p;                    p = G[nex].first;                    while (p->next != NULL) {                        p = p->next;                   }                    p->next = new_node;               }           }       }   } } int main() {    nodelist G;    scanf("%d", &kind);    scanf("%d%d", &num, &edge);    G = new vnode[num];    create(G, kind);    arcnode_p p;    for (int i = 0; i < num; i++) {        printf("%s:   ", G[i].data);        p = G[i].first;        while (p != NULL) {            printf("%s ", G[p->cur].data);            p = p->next;       }   } }
Private Set Intersection(PSI)私有集合交集基本算法金融基础之交易执行

Ross
Ross
这是关于Ross的百科。我将会在这里分享关于编程、机器学习、加密货币的相关内容,有时也会分享一些实用教程或者生活趣事。