I am fairly new to programming in C# and am currently attempting to write the generic classes Graph and GraphNode which I have included below. I understand the logistics behind the methods IsAdjacent and GetNodeByID however I am not to sure how to code these correctly in C# so I have included a small bit of psuedo code in these methods. This however is not the case with the AddEdge method. If possible could you provide me with a solution to these three methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Graph
{
public class GraphNode<T>
{
private T id; //data stored in graph
private LinkedList<T> adjList; //adjacency list
//constructor
public GraphNode(T id)
{
this.id = id;
adjList = new LinkedList<T>();
}
//add an edge from this node : add to to the adjacency list
public void AddEdge(GraphNode<T> to)
{
adjList.AddFirst(to.ID);
}
//set and get for ID – data stored in graph
public T ID
{
set { id = value; }
get { return id; }
}
//returns adjacency list – useful for traversal methods
public LinkedList<T> GetAdjList()
{
return adjList;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Graph
{
public class Graph<T> where T : IComparable
{
//list of GraphNodes in this graph
private LinkedList<GraphNode<T>> nodes;
//constructor - set nodes to new empty list
public Graph()
{
nodes = new LinkedList<GraphNode<T>>();
}
//only return true if the graph’s list of nodes is empty
public bool IsEmptyGraph()
{
return nodes.Count == 0;
}
//Search through list of nodes for node
//Node will be a new graphnode with the
// containing the ID to be search for
public bool ContainsGraph(GraphNode<T> node)
{
//search based on ID
foreach (GraphNode<T> n in nodes)
{
if (n.ID.CompareTo(node.ID) == 0)
return true;
}
return false;
}
//find from in list of nodes and search its adjList for to
public bool IsAdjacent(GraphNode<T> from, GraphNode<T> to)
{
foreach(GraphNode<T> n in nodes)
{
if (n.ID same as from.ID)
{ if (from.AdjList contains to.ID)
return true;
}
return false;
}
}
//add a new graphNode to list of nodes
public void AddNode(T id)
{
GraphNode<T> n = new GraphNode<T>(id);
nodes.AddFirst(n);
}
//Search through list of nodes for node with this ID
public GraphNode<T> GetNodeByID(T id)
{
foreach( GraphNode<T> n in nodes )
{
if (id = n.ID)
{
return n;
}
}
return null;
}
//find from in list of nodes (look at other methods)
//and call graphNode method to add an edge to to
//think about validation here
public void AddEdge(T from, T to)
{
}
//perform a DFS traversal starting at startID, leaving a list
//of visitied ID’s in the visited list.
}
}
Many Thanks