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.
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'm trainee and have a problem with that I can't solve this problem alone. So please help me. I found many topics but I could not find a solution.
I just start to learn C# and I'm not sure how to do this. I know that is a simple job but realy I need to understand and solve it. I try to do something but it is only some code. I did my binary tree with some values, have a node class and print method.
Please tell me how to write a code that can read a tree from the Console, because I don't want to have any hardcorde. And then how to find a lowest common ancestor - I see the BFS and DFS algorithms so maybe I can find something, but I'm not sure.
I've read much about this but I can not explain many things. Her
Here is the my code:
class Program
{
static void Main(string[] args)
{
var binatyTree = new BinaryTree<int>(1,
new BinaryTree<int>(2,
new BinaryTree<int>(4),
new BinaryTree<int>(5)),
new BinaryTree<int>(3,
new BinaryTree<int>(6,
new BinaryTree<int>(9),
new BinaryTree<int>(10)),
new BinaryTree<int>(7))
);
Console.WriteLine("Binary Tree:");
binatyTree.Print();
}
}
my binary tree and print method:
public class BinaryTree<T>
{
public T Value { get; set; }
public BinaryTree<T> LeftChildren { get; set; }
public BinaryTree<T> RightChildren { get; set; }
public BinaryTree(T value, BinaryTree<T> leftChildren = null, BinaryTree<T> rightChildren = null)
{
this.Value = value;
this.LeftChildren = leftChildren;
this.RightChildren = rightChildren;
}
public void Print (int indent = 0)
{
Console.Write(new string (' ', 2*indent));
Console.WriteLine(this.Value);
if (this.LeftChildren != null)
{
this.LeftChildren.Print(indent + 1);
}
if (this.RightChildren != null)
{
this.RightChildren.Print(indent + 1);
}
}
my class Node:
class Node
{
private int data;
private Node left;
private Node right;
public Node(int data = 0)
{
this.data = 0;
left = null;
right = null;
}
}
So please I realy need to understand every connections so please if you can explain for me and help.
So here is my Binary tree code.
using System;
namespace MyBinaryTree
{
// Creates a binary tree
// Finds the lowest common ancestor in a binary tree
class МainSolution
{
static void Main(string[] args)
{
// Initialises binary tree view
var btView = new ViewBinaryTree();
btView.BinaryTreeView();
// Initialises new binary tree
BinarySearchTree tree = new BinarySearchTree();
// Reads the desired number of nodes
Console.Write("Enter how many nodes you want: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine();
// Reads the nodes' values
for (int i = 1; i <= number; i++)
{
Console.Write($"Enter name of {i} node: ");
string nodeName = Console.ReadLine().ToUpper();
tree.Insert(nodeName);
}
// Lowest common ancestor - reads the two required values
// Checks the values
// Prints the lowest common ancestor
bool isValid = true;
while (isValid)
{
Console.WriteLine();
Console.Write("Please enter the first node value: ");
string nameOne = Console.ReadLine().ToUpper();
Console.Write("Please enter the second node value: ");
string nameTwo = Console.ReadLine().ToUpper();
if (tree.Find(nameOne) == true && tree.Find(nameTwo) == true)
{
Console.WriteLine();
var result = tree.SearchLCA(tree.root, nameOne, nameTwo);
Console.WriteLine($"Lowest common ancestor: {result} ");
Console.WriteLine();
isValid = false;
}
else
{
Console.WriteLine();
Console.WriteLine("Please enter a valid name!");
}
}
}
}
}
Create a class Node:
// Creates the node structure
class Node
{
public string Data { get; set; }
public Node RightChild { get; set; }
public Node LeftChild { get; set; }
public Node(string data, Node left = null, Node right = null)
{
this.Data = data;
this.LeftChild = left;
this.RightChild = right;
}
}
Here is my logic
// Creates a binary tree.
class BinarySearchTree
{
public Node root; // Creates a root node.
public BinarySearchTree()
{
this.root = null;
}
// Adds a node in the binary tree.
public void Insert(string inputValue)
{
Node newNode = new Node(inputValue); // Creates a new node.
if (root == null) // If the tree is empty, inserts the new node as root
{
root = newNode;
return;
}
//Determins where to place the new node in the binary tree.
Node current = root;
Node parent = null;
while (true)
{
parent = current;
if (inputValue.CompareTo(current.Data) < 0)
{
current = current.LeftChild;
if (current == null)
{
parent.LeftChild = newNode;
return;
}
}
else
{
current = current.RightChild;
if (current == null)
{
parent.RightChild = newNode;
return;
}
}
}
}
// Checks if the node exists in the binary tree
public bool Find(string inputValue)
{
Node current = root;
while (current != null)
{
if (current.Data.Equals(inputValue))
{
return true;
}
else if (current.Data.CompareTo(inputValue) > 0)
{
current = current.LeftChild;
}
else
{
current = current.RightChild;
}
}
return false;
}
// Creates a method to find the lowest common ancestor(LCA).
public object SearchLCA(Node searchTree, string compareValue1, string compareValue2)
{
if (searchTree == null)
{
return null;
}
if (searchTree.Data.CompareTo(compareValue1) > 0 && searchTree.Data.CompareTo(compareValue2) > 0)
{
return SearchLCA(searchTree.LeftChild, compareValue1, compareValue2);
}
if (searchTree.Data.CompareTo(compareValue1) < 0 && searchTree.Data.CompareTo(compareValue2) < 0)
{
return SearchLCA(searchTree.RightChild, compareValue1, compareValue2);
}
return searchTree.Data;
}
}
"Thank you!"
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.
I am trying to implement a basic Binary search tree.
I was able to create a Node and I have problems with the AddNode() function. It is supposed to add a new node to the existing tree but it replaces it.
Any ideas what should be done in the AddNode() function ?
class Node
{
public int value { get; set; }
public Node left { get; set; }
public Node right { get; set; }
public Node(int i)
{
this.value = i;
this.left = null;
this.right = null;
}
}
class Tree
{
public Node root { get; set; }
public Tree(Node n)
{
root = n;
}
public void AddNode(int valueToBeInserted)
{
if (this.root == null)
{
this.root = new Node(valueToBeInserted);
// problem here : existing tree is destroyed.
// a new one is created.
// instead it should add a new node to the end of the tree if its null
}
if (valueToBeInserted < this.root.value)
{
this.root = this.root.left;
this.AddNode(valueToBeInserted);
}
if (valueToBeInserted > this.root.value)
{
this.root = this.root.right;
this.AddNode(valueToBeInserted);
}
}
public void printTree()
{
// print recursively the values here.
}
}
class TreeTest
{
public void Test()
{
var tree = new Tree(new Node(100));
tree.AddNode(20);
tree.AddNode(100);
}
}
Thanks.
These lines replace the root:
this.root = this.root.left;
this.root = this.root.right;
You should instead pass a parameter to your recursive function.
You can also remove the this quantifiers - they're only necessary when you have a local variable with the same name or perhaps in some other corner cases.
Adding a helper function is useful / necessary since the root must be catered for separately.
Updated code:
public void AddNode(int valueToBeInserted)
{
if (root == null)
{
root = new Node(valueToBeInserted);
}
else
{
AddNode(valueToBeInserted, root);
}
}
private void AddNode(int valueToBeInserted, Node current)
{
if (valueToBeInserted < current.value)
{
if (current.left == null)
current.left = new Node(valueToBeInserted);
else
AddNode(valueToBeInserted, current.left);
}
if (valueToBeInserted > current.value)
{
if (current.right == null)
current.right = new Node(valueToBeInserted);
else
AddNode(valueToBeInserted, current.right);
}
}
This statement will only be true the first time you run your code.
if (this.root == null)
{
this.root = new Node(valueToBeInserted);
}
Nowhere does the this.root get set to null again...
Normally you would code the add like this:
public void AddNode(int valueToBeInserted)
{
if (this.root == null)
{
this.root = new Node(valueToBeInserted);
}
if (valueToBeInserted < this.root.value)
{
this.root.left = this.AddNode(valueToBeInserted);
this.root = this.root.left;
}
if (valueToBeInserted > this.root.value)
{
this.root.right = this.AddNode(valueToBeInserted);
this.root = this.root.right;
}
}
I have the following list:
public class MyQueue : IEnumerable<int>
{
private Node Head { get; set; }
private Node Tail { get; set; }
public MyQueue()
{
Head = null;
}
public void Add(int item)
{
Enqueue(item);
}
public void Enqueue(int item)
{
var newItem = new Node { Data = item };
if (Head == null)
{
Head = newItem;
Tail = newItem;
return;
}
Node last = Tail;
last.Next = newItem;
Tail = newItem;
}
public IEnumerator<int> GetEnumerator()
{
Node current = Head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class Node
{
public int Data;
public Node Next;
}
}
There are other methods, but they do not matter in this scenario.
I'd like to add indexing to this list.
So I can do something like:
var q = new MyQueue() {1, 2};
Console.WriteLine(q[0]); //1
What do I need to implement?
you need to make a property like this:
public int this[int index]
{
get {
// code to return value
}
}
public int this[int index]
{
get
{
return this.Skip(index).FirstOrDefault();
}
}
You need to implement an indexer. An indexer enables you to access a class, struct or interface as if it were an array. The syntax is as follows:
public int this[int index] {
get {
// obtain the item that corresponds to this index
// return the item
}
set {
// set the value of the item that corresponds to
// index to be equal to the implicit parameter named "value"
}
}
Here's an explicit example for your case:
public class MyQueue : IEnumerable<int> {
// ...
public int this[int index] {
get {
if (index < 0 || index > this.Count() - 1) {
throw new ArgumentOutOfRangeException("index");
}
return this.Skip(index).First();
}
set {
if (index < 0) {
throw new ArgumentOutOfRangeException("index");
}
Node current = Head;
int i = 0;
while (current != null && i < index) {
current = current.Next; i++;
}
if (current == null) {
throw new ArgumentOutOfRangeException("index");
}
current.Data = value;
}
}
}
Implement the this operator.
Write a this property, like this: (pun intended)
public int this[int index] {
get {
return something;
}
//Optionally:
set {
something = value;
}
}
Also, you should probably implement IList<int>. (Note, though, that the Count property would require a loop)