Advertisement
shabbyheart

Adjacency list

Dec 6th, 2019
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class Node{
  4. public:
  5.     int destination;
  6.     int weight;
  7.     Node *next;
  8. };
  9. class Integer{
  10. public:
  11.     Node *head = NULL;
  12. };
  13.  
  14. void addEdge(Integer arr[],int sorc,int dest)
  15. {
  16.     Node *newNode = new Node();
  17.     newNode->destination = dest;
  18.     newNode->next = NULL;
  19.     if( arr[sorc].head == NULL)
  20.         arr[sorc].head = newNode;
  21.     else
  22.     {
  23.         Node *temp = arr[sorc].head;
  24.         while(temp->next != NULL)
  25.             temp = temp->next;
  26.         temp->next = newNode;
  27.     }
  28. }
  29.  
  30. void display(Integer listt[], int v)
  31. {
  32.     for(int i =0; i<=v; i++)
  33.     {
  34.         cout<<"\n Adjacency list of vertex "<<i<<" -->";
  35.         while(listt[i].head != NULL)
  36.         {
  37.             cout<<" "<<listt[i].head->destination;
  38.             listt[i].head = listt[i].head->next;
  39.         }
  40.     }
  41.  
  42. }
  43. int main()
  44. {
  45.     freopen("input.txt","r",stdin);
  46.     int v;
  47.     cin>>v;
  48.     Integer arr[v];
  49.  
  50.     /// eita na korle arr er vitore v+1 dite hobe
  51.      for (int i = 0; i <= v; i++)
  52.         arr[i].head = NULL;
  53.  
  54.     /// getting input
  55.     int m,n;
  56.     while(scanf("%d%d",&m,&n) == 2)
  57.     {
  58.         addEdge(arr,m,n);
  59.         addEdge(arr,n,m);
  60.     }
  61.     display(arr,v);
  62. }
  63.  
  64. ///test case:
  65. /*
  66. 7
  67.  
  68. 1 2
  69. 1 3
  70. 2 3
  71. 4 5
  72. 5 6
  73. 5 3
  74. 6 2
  75. 6 4
  76. 3 7
  77. 5 7
  78. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement