linked list implementation of graph code example
Example 1: linkedlist implementation in c++
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
};
int main()
{
linked_list a;
a.add_node(1);
a.add_node(2);
return 0;
}
Example 2: Linked List implementation
public class LinkedList {
private Node head;
private int length = 0;
public LinkedList() {
this.head = new Node(null);
}
public int size() {
return length;
}
public void add(Object data) {
Node node = new Node(data);
Node iterator = head;
while (iterator.getNext() != null){
iterator = iterator.getNext();
}
iterator.setNext(node);
length++;
}
public Object get(int index) {
if (head.getNext() == null || index >= length){
return null;
}
Node iterator = head.getNext();
int counter = 0;
while(counter < index){
iterator = iterator.getNext();
counter++;
}
return iterator.getData();
}
public int indexOf(Object data) {
Node obj=head;
for (int i = 0; i < length; i++) {
obj = obj.getNext();
if (obj.getData().equals(data)) {
return i;
}
}
return -1;
}
public boolean remove(Object data) {
if (head.getNext() == null){
return false;
}
Node iterator = head;
while(iterator.getNext() != null){
if (iterator.getNext().getData().equals(data)){
iterator.setNext(iterator.getNext().getNext());
length--;
return true;
}
iterator = iterator.getNext();
}
return false;
}
private class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
next = null;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}
Example 3: graph c++
#include <bits/stdc++.h>
using namespace std;
class graph
{
vector<int>*adjacency_list;
int Vertices;
public:
graph(int n)
{
Vertices=n;
adjacency_list=new vector<int>[Vertices];
}
void add_edge(int,int);
void display_graph();
};
int main()
{
graph g1(5);
g1.add_edge(0,1);
g1.add_edge(1,2);
g1.add_edge(1,3);
g1.add_edge(2,4);
g1.add_edge(2,3);
cout<<"The entered Graph is "<<endl;
g1.display_graph();
return 0;
}
void graph::add_edge( int u,int v )
{
if( u >= Vertices || v >= Vertices )
{
cout<<"Overflow"<<endl;
return;
}
if( u<0 || v<0 )
{
cout<<"underflow"<<endl;
return;
}
adjacency_list[u].push_back(v);
adjacency_list[v].push_back(u);
}
void graph::display_graph()
{
for(int i=0;i<Vertices;i++)
{
cout<<"Adjacency list of vertex of vertex "<<i<<endl;
for(auto it:adjacency_list[i])
{
cout<<it<<" ";
}
cout<<endl;
}
}