I have created custom linked list in c#.
LinkedList.cs:
class LinkedList
{
private Node Start;//Mazgas pr
private Node End;//Mazgas pb
private Node Current;// Mazas d saraso sasajai
public LinkedList()
{
this.Start = null;
this.End = null;
this.Current = null;
}
public Object Get(int index)
{
for( Node curr = Start; curr != null; curr = curr.Next)
{
if( curr.Index == index )
return curr.Data;
}
return null;
}
public void PrintData()
{
for (Node curr = Start; curr != null; curr = curr.Next)
{
Console.WriteLine("{0}: {1}", curr.Index, curr.Data);
}
}
public int Count()
{
int i = 0;
for( Node curr = Start; curr != null; curr = curr.Next, i++);
return i;
}
public void Add(Object data)
{
Node current = new Node(data, null);
if (Start != null)
{
End.Next = current;
End.Next.Index = End.Index + 1;
End = current;
}
else
{
Start = current;
End = current;
End.Index = 0;
}
}
}
Node.cs:
class Node
{
public Object Data { get; set; }
public Node Next { get; set; }
public int Index { get; set; }
public Node() { }
public Node(Object data, Node next )
{
Data = data;
Next = next;
}
public override string ToString ()
{
return string.Format ("Data: {0}", Data);
}
}
and Part.cs
class Part
{
public string Code { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public Part(string code, string name, double price)
{
Code = code;
Name = name;
Price = price;
}
public Part() { }
public override string ToString()
{
return string.Format("{0} {1}", Name, Code);
}
}
Problem is, when i create list LinkedList parts = new LinkedList()
and add objects to it parts.Add(new Part("code", "name", 10)); i can't access Part object variables. I need to do this:
for( int i=0; i<parts.Count(); i++)
{
Console.WriteLine("{0}", (Part)Parts.Get(i).Name);
}
but it gives me error:
Error CS1061: Type 'object' does not contain a definition for 'Name'
and no extension method 'Name' of type 'object' could be found. Are
you missing an assembly reference? (CS1061)
EDITED: I need this linked list to be flexible for any type of object.
(Part)Parts.Get(i).Name is equivalent to (Part)(Parts.Get(i).Name) and since return value of your Get(i) is of type object and object doesn't have Name property, you received the exception.
You can correct it this way:
((Part)Parts.Get(i)).Name
Note:
I suppose it's just for learning purpose.
If all items of the list are of the same type, you can make your Generic classes. Having a generic Node<T> and LinkedList<T> class you can change the input parameters and return values to T instead of object.
In a real application, you can use LinkedList<T> or other generic data structures available.
Related
Im implementing a stack using a linked list. I am having trouble with my pop method where tail.previous is null. I think this is because im trying to assign to the node after the tail which doesnt exist. if this is the case, how can i fix it.
class DynamicStack<T>
{
private class Node
{
public T element { get; private set; }
public Node Next { get; set; }
public Node Previous { get; set; }
public Node(T element, Node prevNode)
{
this.element = element;
Next = null;
Previous = null;
if (prevNode != null)
prevNode.Next = this;
}
}
private Node head, tail;
public int Count { get; private set; }
public DynamicStack()
{
this.head = null;
this.tail = null;
this.Count = 0;
}
public T Pop()
{
if (Count == 0)
return default(T);
Node temp = tail;
tail = tail.Previous;
Count--;
return temp.element;
}
}
I have tried doing the pop method as below but it doesnt follow LIFO so its not correct.
public T Pop()
{
if (Count == 0)
return default(T);
Node temp = head;
head = head.Next;
Count--;
return temp.element;
}
I am confused as to exactly how classes inherit methods from each other. I already understand inheritance from base classes, there is however, certain code from an example that I do not understand. It involves searching a Binary tree and I could not find any resources that better explain how the code is inherited.
My aim is to understand it so that I can use it to also searched a linkedlist.
If any one can refer me to any relevant literature that explains this particular area I would be grateful.
I have highlighted the code section that I dont really yet understand how it is inhertied. The specific section is posted first:
public Company Read(string bezeichnung)
{
return stri.Search(new Company() { Bezeichnung = bezeichnung });
}
Entire program:
using System;
using System.IO;
using System.Text;
using System.Net;
namespace CompanySearch
{
class Program
{
static void Main(string[] args)
{
StreamReader r = new StreamReader(#"C:\Users\chris\Desktop\algo\fuckit\unternehmen.csv", Encoding.Default);
Companies stri2 = new Companies(r);
while (true)
{
Console.Write("Unternehmensbezeichnung eingeben: ");
string name = Console.ReadLine();
if (string.IsNullOrEmpty(name))
break;
//Company konk = stri2.Read(name);
Company konk = new Company();
konk = stri2.Read(name);
if (konk == null)
Console.WriteLine("Unternehmen nicht gefunden!");
else
Console.WriteLine(konk + "\n");
}
}
}
public class Companies
{
private BinaryTree<Company> stri = new BinaryTree<Company>();
public Companies(StreamReader rp)
{
// Spaltenüberschriften auslesen
//var tokens = rp.ReadLine().Split(new char[] { ';' });
//if (tokens.Length != 3)
// throw new ArgumentException("More than 3 columns in company file");
string line;
while ((line = rp.ReadLine()) != null)
{
var tokens = line.Split(new char[]{';'});
//tokens = line.Split(new char[] { ';' });
stri.Add(new Company()
{Bezeichnung = tokens[0], Branche = tokens[1], Ort = tokens[2]});
}
rp.Close();
}
public Company Read(string bezeichnung)
{
return stri.Search(new Company()
{Bezeichnung = bezeichnung});
}
}
public class Company : IComparable<Company>
{
public string Bezeichnung
{
get;
set;
}
public string Branche
{
get;
set;
}
public string Ort
{
get;
set;
}
public int CompareTo(Company other)
{
return Bezeichnung.CompareTo(other.Bezeichnung);
}
public override string ToString()
{
return string.Format("Bezeichnung: {0}\tBranche: {1}\tOrt: {2}", Bezeichnung, Branche, Ort);
}
}
public enum TraverseModeEnum
{
PreOrder,
PostOrder,
InOrder,
ReverseInOrder
}
public class BinaryTree<T>
where T : IComparable<T>
{
private sealed class Node<TNode>
where TNode : IComparable<TNode> // TNode muss IComparable implementieren
{
public TNode Item
{
get;
set;
}
public Node<TNode> Left
{
get;
set;
}
public Node<TNode> Right
{
get;
set;
}
public int CompareTo(TNode other)
{
return Item.CompareTo(other);
}
}
private Node<T> root;
public int Count
{
get;
private set;
}
public TraverseModeEnum TraverseMode
{
get;
set;
}
public BinaryTree()
{
TraverseMode = TraverseModeEnum.PreOrder;
}
public void Add(T item)
{
if (root == null)
root = new Node<T>()
{Item = item};
else
addTo(root, item);
Count++;
}
public void AddRange(T[] items)
{
foreach (var item in items)
Add(item);
}
private void addTo(Node<T> node, T item)
{
if (item.CompareTo(node.Item) < 0)
{
if (node.Left == null)
node.Left = new Node<T>()
{Item = item};
else
addTo(node.Left, item);
}
else
{
if (node.Right == null)
node.Right = new Node<T>()
{Item = item};
else
addTo(node.Right, item);
}
}
public bool Contains(T item)
{
Node<T> node = root;
while (node != null)
{
int c = node.Item.CompareTo(item);
if (c == 0)
return true;
if (c > 0)
node = node.Left;
else
node = node.Right;
}
return false;
}
public T Search(T item)
{
Node<T> node = root;
while (node != null)
{
int c = node.Item.CompareTo(item);
if (c == 0)
return node.Item;
if (c > 0)
node = node.Left;
else
node = node.Right;
}
return default (T);
}
public void Clear()
{
root = null;
Count = 0;
}
public override string ToString()
{
string s = "";
int level = 0;
traverse(root, level, ref s);
return s;
}
private void traverse(Node<T> node, int level, ref string s)
{
if (node == null)
return;
bool reverse = TraverseMode == TraverseModeEnum.ReverseInOrder;
if (TraverseMode == TraverseModeEnum.PreOrder)
s += "".PadLeft(level, ' ') + node.Item.ToString() + "\n";
traverse(reverse ? node.Right : node.Left, level + 2, ref s);
if (TraverseMode == TraverseModeEnum.InOrder || TraverseMode == TraverseModeEnum.ReverseInOrder)
s += "".PadLeft(level, ' ') + node.Item.ToString() + "\n";
traverse(reverse ? node.Left : node.Right, level + 2, ref s);
if (TraverseMode == TraverseModeEnum.PostOrder)
s += "".PadLeft(level, ' ') + node.Item.ToString() + "\n";
}
}
}
The class BinaryTree<T> down in the code demands that T must implement IComparable<T>. Lots of list-ish classes make similar demands. If a type implements IComparable<T> it means two instances of a class can be compared to each other with the ComparetTo( T t1, T t2 ) method. This method returns an indication of which T is greater than, less than, or equal to the other. Realize that the greater than, less than, or equal to is entirely up to the type that implements the interface. It's principally used for sorting or otherwise locating things in a tree, list, or other structure based on the comparison.
Implementing an interface looks like class inheritance. The syntax is the same...but it's more like a contract, since an interface has no code to inherit. If you make a class that goes like:
class MyClass: IComparable<MyClass>
{
//--> stuff
}
...then you're obligated to have a publicly visible method with the signature:
int CompareTo( MyClass a, MyClass b )
{
//--> look at the two instances and make a determination...
}
The method can use any characteristics of the class to determine what makes a greater than, less than, or equal to b...and thereby control how it's going to be placed into a structure.
A class can inherit from only one other class...but it can implement as many interfaces as it needs. This is what, I'm guessing, looks like multiple inheritance.
a. There is no real inheritance in your code. Only the implementation of a standard interface, IComparable<T>. Implementing an interface is sometimes called inheritance but it is not the same. In this case it forces Company to implement the CompareTo() method.
b. The code you have a question about just creates a temporary object. You can rewrite it to something that might be easier to understand:
//return stri.Search(new Company() { Bezeichnung = bezeichnung });
var tempCompany = new Company() { Bezeichnung = bezeichnung };
return stri.Search(tempCompany);
I keep getting an unhandled exception
"Object reference not set to an instance of an object"
for the following code, specifically on the line temp.next = node. Can anyone help me figure out why?
The code below is a class for birds where the user inputs a name and the addBird method is suppose to add the name to the end of the linked list.
class BirdsSurve {
private Node first;
public class Node
{
public string Name { get; set; }
public int count { get; set; }
public Node next;
public Node()
{
this.count = 1;
}
public void setNext(Node Next)
{
next = Next;
}
public int addCount()
{
count++;
return count;
}
}
public BirdsSurvey()
{
this.first = null;
}
public void addBird(string bird)
{
Node node = new Node();
node.Name = bird;
if (first == null)
{ first = node; }
else
{
Node temp = first;
while (temp != null)
{
if (temp.Name == bird)
{ temp.addCount(); }
if (temp.next == null)
{
temp = temp.next;
temp.next = node; }
// temp = temp.next;
}
}
}
You set temp to temp.next within the if clause, which checks, if temp.next is null. So, you basically set temp to be null. So, you get the error, because you try to get a next property from a variable, which is null and not an object.
As a side note, maybe rethink the naming of your variables, so that they are not all the same, because that can become confusing quite fast.
I have following code:
public string Longest
{
get
{
int min = int.MinValue;
string longest = "";
for (Node i = Head; i != null; i = i.Next)
{
if (i.Text.Length > min)
{
longest = i.Text.Length.ToString();
}
return longest;
}
return longest;
}
}
The problem is I have those strings:
List text = new List();
text.Add("Petar");
text.Add("AHS");
text.Add("Google");
text.Add("Me");
When I try out the propertie it says that the longest string is 5 but thats not true the longest string is six. I've tried to find out where my problem but i coulnd't find it.
Your code has a couple of problems:
A length can be, as minimum, 0, so you don't need to use int.MinValue
You are returning on the first iteration
You are not updating min after finding a longer value
You are returning the length of the string, not the string itself
Your code should look like this:
public string Longest
{
get
{
int longestLength = 0;
string longestWord = string.Empty;
for (Node i = Head; i != null; i = i.Next)
{
if (i.Text.Length > longestLength)
{
longestLength = i.Text.Length;
longestWord = i.Text;
}
}
return longestWord;
}
}
If what you want to return is the maximum length instead of the word with the maximum length, your property is both wrongly named and typed, and it should look like this instead:
public int MaximumLength
{
get
{
int maximumLength = 0;
for (Node i = Head; i != null; i = i.Next)
{
if (i.Text.Length > maximumLength)
{
maximumLength = i.Text.Length;
}
}
return maximumLength;
}
}
If you have an IEnumerable<string> then do the following
var list = new List<string>();
list.Add("AAA");
list.Add("AAAAA");
list.Add("A");
list.Add("AAAA");
list.Add("AAAAAA");
list.Add("AA");
// max has the longest string
var max = list.Aggregate(string.Empty,
(bookmark, item) => item.Length>bookmark.Length ? item : bookmark);
or using a loop
string max = string.Empty;
int length=0;
foreach(var item in list)
{
if(item.Length>length)
{
max = item;
length = item.Length;
}
}
But it appears you have a linked list which I recreated as a skeleton below:
public class Node
{
public Node(string text)
{
this.Text = text;
this.Head = this;
}
public Node(Node parent, string text): this(text)
{
if(parent!=null)
{
parent.Next = this;
this.Head = parent.Head;
}
}
public Node Head { get; }
public Node Next { get; set; }
public string Text { get; }
public Node Add(string text) => new Node(this, text);
}
and finding the longest string with a loop is
var list = new Node("AAA");
list = list.Add("AAAAA");
list = list.Add("A");
list = list.Add("AAAA");
list = list.Add("AAAAAA");
list = list.Add("AA");
string max = list.Text;
int length = max.Length;
for(Node node = list.Head; node != null; node = node.Next)
{
if(node.Text.Length > length)
{
max = node.Text;
length= node.Text.Length;
}
}
// max has the longest string
Edit 1
I took the linked list and made it IEnumerable<string> by moving your loop code into a method:
public class Node : IEnumerable<string>
{
public Node(string text)
{
this.Text = text;
this.Head = this;
}
public Node(Node parent, string text) : this(text)
{
if(parent!=null)
{
parent.Next = this;
this.Head = parent.Head;
}
}
public Node Head { get; }
public Node Next { get; set; }
public string Text { get; }
public Node Add(string text) => new Node(this, text);
public IEnumerator<string> GetEnumerator()
{
// Loop through the list, starting from head to end
for(Node node = Head; node != null; node = node.Next)
{
yield return node.Text;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
and now I can use a single LINQ statement
var list = new Node("AAA");
list = list.Add("AAAAA");
list = list.Add("A");
list = list.Add("AAAA");
list = list.Add("AAAAAA");
list = list.Add("AA");
// max has the longest string
var max = list.Aggregate(string.Empty,
(bookmark, item) => item.Length>bookmark.Length ? item : bookmark);
This is a entity and i want to list all the children node for a given node in a generic function
public static List<T> BuildTree<T>(List<T> list, T selectNode string keyPropName, string parentPropName, string levelPropName, int level = 0)
{
List<T> entity = new List<T>();
foreach (T item in list)
{
}
return entity;
}
example of the entity structure
protected long _coakey;
protected long _parentkey;
protected string _coacode;
protected string _coacodeclient;
protected string _coaname;
protected int _coalevel;
[DataMember]
public long coakey
{
get { return _coakey; }
set { _coakey = value; this.OnChnaged(); }
}
[DataMember]
public long parentkey
{
get { return _parentkey; }
set { _parentkey = value; this.OnChnaged(); }
}
[DataMember]
public string coacode
{
get { return _coacode; }
set { _coacode = value; this.OnChnaged(); }
}
[DataMember]
public string coacodeclient
{
get { return _coacodeclient; }
set { _coacodeclient = value; this.OnChnaged(); }
}
[DataMember]
public string coaname
{
get { return _coaname; }
set { _coaname = value; this.OnChnaged(); }
}
[DataMember]
public int coalevel
{
get { return _coalevel; }
set { _coalevel = value; this.OnChnaged(); }
}
Your BuildTree<T> method cannot determine the structure of the tree unless it knows something about its structure. At a very minimum, I would suggest making a base class or interface that defines a tree node, and then change the BuildTree method to work specifically with those types of objects. Then, it will be able to figure out the tree structure. Each of you entity classes would have to implement that tree node interface or inherit from the tree node base class. For instance:
public abstract class TreeNodeBase
{
public long parentkey
{
get { return _parentkey; }
set { _parentkey = value; this.OnChanged(); }
}
protected long _parentkey;
}
public class MyEntityTreeNode : TreeNodeBase
{
public long coakey
{
get { return _coakey; }
set { _coakey = value; this.OnChanged(); }
}
protected long _coakey;
// etc...
}
// Note the generic type constraint at the end of the next line
public static List<T> BuildTree<T>(List<T> list, T selectNode, string keyPropName, string parentPropName, string levelPropName, int level) where T : TreeNodeBase
{
List<T> entity = new List<T>();
foreach (TreeNodeBase node in list)
{
long parentKey = node.parentkey;
// etc...
}
return entity;
}
Node class:
public class Node<TKey, TValue> where TKey : IEquatable<TKey>
{
public TKey Key { get; set; }
public TKey ParentKey { get; set; }
public TValue Data { get; set; }
public readonly List<Node<TKey, TValue>> Children = new List<Node<TKey, TValue>>();
}
TreeBuilder:
public static Node<TKey, TValue> BuildTree<TKey, TValue>(IEnumerable<Node<TKey, TValue>> list,
Node<TKey, TValue> selectNode)
where TKey : IEquatable<TKey>
{
if (ReferenceEquals(selectNode, null))
{
return null;
}
var selectNodeKey = selectNode.Key;
foreach (var childNode in list.Where(x => x.ParentKey.Equals(selectNodeKey)))
{
selectNode.Children.Add(BuildTree(list, childNode));
}
return selectNode;
}
Usage:
List<MyClass> list = ...
var nodes = list.Select(x => new Node<long, MyClass>
{
Key = x.MyKey,
ParentKey = x.MyParentKey,
Data = x
}).ToList();
var startNode = nodes.FirstOrDefault(x => x.Data.Stuff == "Pick me!");
var tree = BuildTree(nodes, startNode);
MyClass example:
public class MyClass
{
public long MyKey;
public long MyParentKey;
public string Name;
public string Text;
public string Stuff;
}
I have solved it my self hope it help you
public static List<T> BuildTree<T>(List<T> list, T selectedNode, string keyPropName, string parentPropName, int endLevel = 0, int level = 0)
{
List<T> entity = new List<T>();
Type type = typeof(T);
PropertyInfo keyProp = type.GetProperty(keyPropName);
string _selectedNodekey = keyProp.GetValue(selectedNode, null).ToString();
PropertyInfo parentProp = type.GetProperty(parentPropName);
foreach (T item in list)
{
string _key = keyProp.GetValue(item, null).ToString();
string _parent = parentProp.GetValue(item, null).ToString();
if (_selectedNodekey == _parent)
{
T obj = (T)Activator.CreateInstance(typeof(T));
obj = item;
entity.Add(obj);
if (level == endLevel && level!=0) break;
entity.AddRange(BuildTree<T>(list, obj, keyPropName, parentPropName, level + 1));
}
}
return entity;
}