using adjacent list to describe undirected graph
#include <iostream>
#include <cstdlib>
using namespace std;
struct list
{
int val;
struct list *next;
};
typedef struct list node;
typedef node *link;
struct list head[6];
int main()
{
link ptr, newnode;
int data[14][2] = {{1,2},{2,1},{1,5},{5,1},{2,3},{3,2},{2,4},{4,2},
{3,4},{4,3},{3,5},{5,3},{4,5},{5,4}};
cout << "The adjacent list of the graph : \n";
for(int i = 1; i < 6; i++)
{
head[i].val = i;
head[i].next = NULL;
cout << "Vertix " << i << " => ";
ptr = &(head[i]);
for(int j = 0; j < 14; j++)
{
if(data[j][0] == i)
{
newnode = (link)malloc(sizeof(node));
newnode->val = data[j][1];
newnode->next = NULL;
while(ptr != NULL)
ptr = ptr->next;
ptr = newnode;
cout << "[" << newnode->val << "] ";
}
}
cout << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Filed under: Data Structure | Tagged: graph, linked_list