mafulechka
July 1, 2019, 2:22 p.m.

Adjacency list

Adjacency List represents a graph as an array of linked list.


The array index represents a vertex and each element in its linked list, and also represents other vertices that form an edge with the vertex.

Representing adjacency list

The graph and its equivalent adjacency list representation are shown below.

The adjacency list is storage efficient because we only need to store values for edges. For a sparse graph with millions of vertices and edges, this can mean a lot of space saved.

The structure of the adjacency list

The simplest adjacency list requires a node data structure to store the vertex and a graph data structure to organize the nodes.

We are approaching the basic definition of a graph - the collection of vertices and edges {V, E}. For simplicity, we use an unlabeled graph, not a labeled one, that is, the vertices are identified by their indices 0,1,2,3.

Let's take a look at the data structure below.

  1. struct node
  2. {
  3. int vertex;
  4. struct node* next;
  5. };
  6. struct Graph
  7. {
  8. int numVertices;
  9. struct node** adjLists;
  10. };

Don't let struct node* adjLists overwhelm you.
We need to save the struct node
pointer. Because we don't know how many vertices there will be in the graph, we can't create an array of linked lists at compile time.

Adjacency List C++

It's the same structure, but with C++'s built-in list of STL data structures, we make the structure a bit cleaner. We can also abstract away implementation details.

  1. class Graph
  2. {
  3. int numVertices;
  4. list<int> *adjLists;
  5.  
  6. public:
  7. Graph(int V);
  8. void addEdge(int src, int dest);
  9. };

Java adjacency list

We are using Java Collections to store an array of linked lists.

  1. class Graph
  2. {
  3. private int numVertices;
  4. private LinkedList<integer> adjLists[];
  5. }

The LinkedList type determines what kind of data you want to store in it. For a labeled graph, you can store a dictionary instead of an integer value.

Python adjacency list

There's a reason why Python gets so much "love". A simple dictionary of vertices and its edges is a sufficient representation of a graph. You can make the top as complex as you like.

  1. graph = {'A': set(['B', 'C']),
  2. 'B': set(['A', 'D', 'E']),
  3. 'C': set(['A', 'F']),
  4. 'D': set(['B']),
  5. 'E': set(['B', 'F']),
  6. 'F': set(['C', 'E'])}

C adjacency list code

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6. int vertex;
  7. struct node* next;
  8. };
  9. struct node* createNode(int);
  10. struct Graph
  11. {
  12. int numVertices;
  13. struct node** adjLists;
  14. };
  15. struct Graph* createGraph(int vertices);
  16. void addEdge(struct Graph* graph, int src, int dest);
  17. void printGraph(struct Graph* graph);
  18. int main()
  19. {
  20. struct Graph* graph = createGraph(6);
  21. addEdge(graph, 0, 1);
  22. addEdge(graph, 0, 2);
  23. addEdge(graph, 1, 2);
  24. addEdge(graph, 1, 4);
  25. addEdge(graph, 1, 3);
  26. addEdge(graph, 2, 4);
  27. addEdge(graph, 3, 4);
  28. addEdge(graph, 4, 6);
  29. addEdge(graph, 5, 1);
  30. addEdge(graph, 5, 6);
  31.  
  32. printGraph(graph);
  33.  
  34. return 0;
  35. }
  36.  
  37.  
  38. struct node* createNode(int v)
  39. {
  40. struct node* newNode = malloc(sizeof(struct node));
  41. newNode->vertex = v;
  42. newNode->next = NULL;
  43. return newNode;
  44. }
  45.  
  46. struct Graph* createGraph(int vertices)
  47. {
  48. struct Graph* graph = malloc(sizeof(struct Graph));
  49. graph->numVertices = vertices;
  50.  
  51. graph->adjLists = malloc(vertices * sizeof(struct node*));
  52.  
  53. int i;
  54. for (i = 0; i < vertices; i++)
  55. graph->adjLists[i] = NULL;
  56.  
  57. return graph;
  58. }
  59.  
  60. void addEdge(struct Graph* graph, int src, int dest)
  61. {
  62. // Add edge from src to dest
  63. struct node* newNode = createNode(dest);
  64. newNode->next = graph->adjLists[src];
  65. graph->adjLists[src] = newNode;
  66.  
  67. // Add edge from dest to src
  68. newNode = createNode(src);
  69. newNode->next = graph->adjLists[dest];
  70. graph->adjLists[dest] = newNode;
  71. }
  72.  
  73. void printGraph(struct Graph* graph)
  74. {
  75. int v;
  76. for (v = 0; v < graph->numVertices; v++)
  77. {
  78. struct node* temp = graph->adjLists[v];
  79. printf("\n Adjacency list of vertex %d\n ", v);
  80. while (temp)
  81. {
  82. printf("%d -> ", temp->vertex);
  83. temp = temp->next;
  84. }
  85. printf("\n");
  86. }
  87. }

C++ adjacency list code

  1. #include <iostream>
  2. #include <list>
  3. using namespace std;
  4.  
  5. class Graph
  6. {
  7. int numVertices;
  8. list *adjLists;
  9.  
  10. public:
  11. Graph(int V);
  12. void addEdge(int src, int dest);
  13. };
  14.  
  15. Graph::Graph(int vertices)
  16. {
  17. numVertices = vertices;
  18. adjLists = new list[vertices];
  19. }
  20.  
  21. void Graph::addEdge(int src, int dest)
  22. {
  23. adjLists[src].push_front(dest);
  24. }
  25.  
  26.  
  27. int main()
  28. {
  29. Graph g(4);
  30. g.addEdge(0, 1);
  31. g.addEdge(0, 2);
  32. g.addEdge(1, 2);
  33. g.addEdge(2, 3);
  34.  
  35. return 0;
  36. }

Java adjacency list code

  1. import java.io.*;
  2. import java.util.*;
  3. class Graph
  4. {
  5. private int numVertices;
  6. private LinkedList<Integer> adjLists[];
  7.  
  8. Graph(int vertices)
  9. {
  10. numVertices = vertices;
  11. adjLists = new LinkedList[vertices];
  12.  
  13. for (int i = 0; i < vertices; i++)
  14. adjLists[i] = new LinkedList();
  15. }
  16.  
  17. void addEdge(int src, int dest)
  18. {
  19. adjLists[src].add(dest);
  20. }
  21.  
  22. public static void main(String args[])
  23. {
  24. Graph g = new Graph(4);
  25.  
  26. g.addEdge(0, 1);
  27. g.addEdge(0, 2);
  28. g.addEdge(1, 2);
  29. g.addEdge(2, 3);
  30. }
  31. }

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html