I'm making a basic LinkedList following this tutorial. However, when I'm done the list only contains two elements, "first" and "fourth". I put some break points in the code and found that the Add function of the LinkedList class only runs once. Each succesive Add goes into the Node(object data) method of the Node class. Any idea what I'm doing wrong?
public class Node
{
public object data;
public Node next;
public Node(object data)
{
this.data = data;
}
}
public class LinkedList
{
private Node head;
private Node current;
public void Add(Node n)
{
if (head == null)
{
head = n;
current = head;
}
else
{
current.next = n;
current = current.next;
}
}
}
class Program
{
static void Main(string[] args)
{
LinkedList list = new LinkedList();
list.Add(new Node("first"));
list.Add(new Node("second"));
list.Add(new Node("third"));
list.Add(new Node("fourth"));
}
}
Using this basic print method with your code :
public void Print()
{
Node curr = head;
while(true)
{
if(curr == null)
return;
Console.WriteLine(curr.data.ToString());
curr = curr.next;
}
}
Return the correct result : live example.
first
second
third
fourth
Your error must be with your printing routine.
There is no problem with your code, i guess you are checking only the LinkedList nodes while debugging, which will only shows the head and the current values.
Just try this,
class Program
{
static void Main(string[] args)
{
LinkedList list = new LinkedList();
list.Add(new Node("first"));
list.Add(new Node("second"));
list.Add(new Node("third"));
list.Add(new Node("fourth"));
list.PrintNodes();
}
}
public class Node
{
public object data;
public Node next;
public Node(object data)
{
this.data = data;
}
}
public class LinkedList
{
private Node head;
private Node current;
public void Add(Node n)
{
if (head == null)
{
head = n;
current = head;
}
else
{
current.next = n;
current = current.next;
}
}
public void PrintNodes()
{
while (head != null)
{
Console.WriteLine(head.data);
head = head.next;
}
Console.ReadLine();
}
}
Related
I have a class Program which is a list of Nodes that contain a method IEnumerator Invoke() and the Program class iterates through each Node invoking it. I want to be able to provide methods to Start, Pause, Resume, and Stop execution. Starting would cause the invocation to start at the top of the list, Pausing would effectively 'Stop' the execution and allow Resume to be able to pick up wherever execution was when Pause was called, and Stop would cease all function and would require Start to be called to begin again. With Unity's built-in Coroutines is this even possible, and if it is how do I Pause/Resume a coroutine?
EDIT
what I'm looking for is how to essentially pause an instance of Program and be able to resume it at the same step.
If I understand one of the comments correctly the suggestion it makes would be something similar to this?
public abstract class Node {
public abstract IEnumerator Invoke(ProgramCaller caller);
}
public class Program : Node {
private List<Node> nodes;
public override IEnumerator Invoke(ProgramCaller caller) {
int index = 0;
while(index < nodes.Count) {
if(caller.Paused) {
yield return null;
}
else {
yield return nodes[index].Invoke(caller);
index++;
}
}
}
}
So from what I read is you have e.g.
public class Node
{
public IEnumerator Invoke()
{
yield return null;
}
}
Then a Unity Coroutine is basically using the IEnumerator and invoking MoveNext on certain intervals (Update by default except using the special ones like e.g. WaitForFixedUpdate etc).
So you could simply make Program implement that like e.g.
public class Program : IEnumerator
{
public Node[] nodes;
private int index = -1;
private IEnumerator currentNode;
public bool MoveNext()
{
if (nodes == null || nodes.Length == 0)
{
return false;
}
while (currentNode == null)
{
index++;
if (index >= nodes.Length)
{
return false;
}
currentNode = nodes[index]?.Invoke();
}
if (currentNode.MoveNext())
{
return true;
}
currentNode = null;
return true;
}
public void Reset()
{
index = -1;
currentNode = null;
}
public object Current => null;
}
and then you can link this up to a Coroutine from a MonoBehaviour like e.g.
public class Example : MonoBehaviour
{
public Program program;
private Coroutine currentRoutine;
// just a name alias
public void StartProgram() => RestartProgram();
public void RestartProgram()
{
StopProgram();
ResumeProgram();
}
public void ResumeProgram()
{
currentRoutine = StartCoroutine(program);
}
public void PauseProgram()
{
if (currentRoutine != null)
{
StopCoroutine(currentRoutine);
}
}
public void StopProgram()
{
PauseProgram();
program.Reset();
}
}
as you see the only difference between Start/Stop and Pause/Resume is resetting or not resetting the Program.
Alternatively and maybe even more simple: A Coroutine is paused automatically when disabling according MonoBehaviour and resumed when enabling it again.
=> If it is an option for you to have a dedicated runner component for each program then all you need really is the resetting part and you could simply do
public class Program
{
public Node[] nodes;
public IEnumerator Run()
{
foreach (var node in nodes)
{
yield return node.Invoke();
}
}
}
This way you can run them all as a single IEnumerator and then
public class Example : MonoBehaviour
{
public Program program;
private Coroutine currentRoutine;
// just a name alias
public void StartProgram() => RestartProgram();
public void RestartProgram()
{
StopProgram();
currentRoutine = StartCoroutine(program.Run());
}
public void ResumeProgram()
{
enabled = true;
}
public void PauseProgram()
{
enabled = false;
}
public void StopProgram()
{
if (currentRoutine != null)
{
StopCoroutine(currentRoutine);
}
}
}
I have a project that requires us to use linked list stacks(NodeStack) and queues(NodeQueue). I have this sample code to work with:
class Node
{
object value;
Node next;
public void setValue(object o)
{
value = o;
}
public object getValue()
{
return value;
}
public void setNext(Node o)
{
next = o;
}
public Node getNext()
{
return next;
}
}
class NodeStack
{
Node top;
int count;
public void Push(object o)
{
Node newTop = new Node();
newTop.setValue(o);
newTop.setNext(top);
top = newTop;
count = count + 1;
}
public object Pop()
{
object value = top.getValue();
top = top.getNext();
return value;
}
public object Peek()
{
return top.getValue();
}
public void Clear()
{
top = null;
count = 0;
}
public int Count()
{
return count;
}
}
From this code I should be able to derive the NodeStack to a NodeQueuebut I have trouble understanding the syntax for the Enqueue and Dequeue methods. When I run a simple enqueue and dequeue program I get a Null reference exception on the 1st line of the dequeue method. Really appreciate the help.
Code I have so far:
class NodeQueue
{
Node tail;
Node head;
int count;
public void Enqueue(object o)
{
if (head == null)
{
Node newHead = new Node();
newHead.setValue(o);
head = tail = newHead;
newHead.setNext(tail);
}
else
{
Node newTail = new Node();
newTail.setValue(o);
newTail.setNext(tail);
tail = newTail;
}
count++;
}
public object Dequeue()
{
object value = head.getValue();
head = head.getNext();
return value;
}
public void Clear()
{
head = null;
tail = null;
count = 0;
}
public int Count()
{
return count;
}
}
EDIT:
The problem with the NullException has been handled but now I have a problem with dequeue. I am using this program to test the queue
NodeQueue nq = new NodeQueue();
nq.Enqueue(1);
nq.Enqueue(2);
nq.Enqueue(3);
nq.Enqueue(4);
nq.Enqueue(5);
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.ReadLine();
The expected output would be 1..5. The output that happens though is that 1 keeps getting printed.
Your Enqueuemethod is not correct thats why your are getting exception in 'Dequeue`
Also in Dequeue you should reduce count by one.
In your Enqueue head is not set.
class NodeQueue
{
Node tail;
Node head;
int count;
public void Enqueue(object o)
{
if (head == null)
{
Node newHead = new Node();
newHead.setValue(o);
head = tail = newHead;
}
else
{
Node newTail = new Node();
newTail.setValue(o);
tail.setNext(newTail);
tail = newTail;
}
count++;
}
public object Dequeue()
{
if (null != head)
{
object value = head.getValue();
head = head.getNext();
count--;
return value;
}
return null;
}
public void Clear()
{
head = null;
tail = null;
count = 0;
}
public int Count()
{
return count;
}
}
I have written a code in C# for the implementation of AVL_trees. I am having some problems with nodes that's why I am unable to insert data in the nodes. Below is my code.
public class avl_node
{
public int Data;
public avl_node Left;
public avl_node Right;
public int height;
public void DisplayNode()
{
Console.Write("{0}", Data);
}
}
public class avl_tree
{
public avl_node root;
public avl_tree()
{
root = null;
}
public void Insert(int i)
{
avl_node newNode = new avl_node();
newNode.Data = i;
newNode.height = newNode.height + 1;
if (root == null)
{
root = newNode;
}
else
{
avl_node current = root;
avl_node parent;
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
}
}
}
public void InOrder(avl_node node)
{
if (!(node == null))
{
InOrder(node.Left);
node.DisplayNode();
InOrder(node.Right);
}
}
}
class Program
{
static void Main(string[] args)
{
avl_tree nums = new avl_tree();
nums.Insert(23);
nums.Insert(45);
nums.Insert(16);
nums.Insert(37);
nums.Insert(3);
nums.Insert(99);
nums.Insert(22);
avl_node nd = new avl_node();
nd = nums.Search(37);
Console.WriteLine("Inorder traversal: ");
nums.InOrder(nums.root);
}
}
All I get is a black console screen. I am very confused.
Hoping for a better response.
Regards
Umer
"All I get is a black console screen"
After 23 is inserted, your Insert() method gets stuck in the while loop because 45 is never less than 23:
while (true)
{
parent = current;
if (i < current.Data)
// you never get in here, so we just loop around in "while (true)"
Take a look at that loop in the insert method, you will get stuck in the loop everytime you try to insert any value greater than existing values already in the tree.
It will happen because of this conditional: if(i < current.data).
Where is the else statement? You put it inside the scope of the mentioned conditional. So it will never be reached, thus the program will run the infinite loop.
You should put an "}" before the else statement, so that else will be outside the scope of the first if statement. And Remove one of the "}" at the end of the method.
That way it should run just fine.
I have a ViewState holding a List<T>
public List<AwesomeInt> MyList
{
get { return ((List<int>)ViewState["MyIntList"]).Select(i => new AwesomeInt(i)).ToList(); }
set { ViewState["MyIntList"] = value.GetIntegers(); }
}
Now, when I call MyList.Add(new AwesomeInt(3)) let's say, the list does not persist the change.
I believe this is because the .ToList() in the get is creating a new List object and therefore the set will never be called, thus never saving in ViewState.
I have worked around this problem before by either
not calling .Select/.ToList() by saving/calling directly without a
conversion.
not using the .Add or .Remove functions and instead
re-initializing the List with an equals.
However sometimes 1. is impractical if the class is not serializable and I have no control over that, and 2. is kind of ugly because I have to copy it to a temp first, then add, then re-assign, or play around with Concat to add a single item.
Is there a better way of doing this?
Alright, below is a fully functional console application that should give you the capabilities you need. I leveraged generics so that you could build surrounding collections of whatever type necessary - but yet serialize something more rudimentary. Keep in mind I don't have a real view state to write to in the set but you can fix that up.
Also bear in mind I wrote this in a pretty short time frame (e.g. 20 minutes) so there may be optimizations that exist (e.g. the set on the ViewState property isn't really necessary generally because this solution modifies the underlying rudimentary data source).
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static List<int> _viewState = new List<int>();
static RawCollection<AwesomeInt, int> ViewState
{
get { return new RawCollection<AwesomeInt, int>(_viewState); }
set { _viewState = value.RawData; }
}
static void Main(string[] args)
{
ViewState.Add(new AwesomeInt(1));
ViewState.Add(new AwesomeInt(2));
WriteViewState();
ViewState[0].Val = 5;
WriteViewState();
ViewState.RemoveAt(0);
WriteViewState();
for (int i = 10; i < 15; i++)
{
ViewState.Add(new AwesomeInt(i));
}
WriteViewState();
}
private static void WriteViewState()
{
for (int i = 0; i < ViewState.Count; i++)
{
Console.WriteLine("The value at index {0} is {1}.", i, ViewState[i].Val);
}
Console.WriteLine();
Console.WriteLine();
}
}
public class RawCollection<T, K> : Collection<T>
{
private List<K> _data;
public RawCollection(List<K> data)
{
foreach (var i in data)
{
var o = (T)Activator.CreateInstance(typeof(T), i);
var oI = o as IRawData<K>;
oI.RawValueChanged += (sender) =>
{
_data[this.IndexOf((T)sender)] = sender.Val;
};
this.Add(o);
}
_data = data;
}
public List<K> RawData
{
get
{
return new List<K>(
this.Items.Select(
i => ((IRawData<K>)i).Val));
}
}
protected override void ClearItems()
{
base.ClearItems();
if (_data == null) { return; }
_data.Clear();
}
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
if (_data == null) { return; }
_data.Insert(index, ((IRawData<K>)item).Val);
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
if (_data == null) { return; }
_data.RemoveAt(index);
}
protected override void SetItem(int index, T item)
{
base.SetItem(index, item);
if (_data == null) { return; }
_data[index] = ((IRawData<K>)item).Val;
}
}
public class AwesomeInt : IRawData<int>
{
public AwesomeInt(int i)
{
_val = i;
}
private int _val;
public int Val
{
get { return _val; }
set
{
_val = value;
OnRawValueChanged();
}
}
public event Action<IRawData<int>> RawValueChanged;
protected virtual void OnRawValueChanged()
{
if (RawValueChanged != null)
{
RawValueChanged(this);
}
}
}
public interface IRawData<T> : INotifyRawValueChanged<T>
{
T Val { get; set; }
}
public interface INotifyRawValueChanged<T>
{
event Action<IRawData<T>> RawValueChanged;
}
}
I wrote this quickly under interview conditions, I wanted to post it to the community to possibly see if there was a better/faster/cleaner way to go about it. How could this be optimized?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stack
{
class StackElement<T>
{
public T Data { get; set; }
public StackElement<T> Below { get; set; }
public StackElement(T data)
{
Data = data;
}
}
public class Stack<T>
{
private StackElement<T> top;
public void Push(T item)
{
StackElement<T> temp;
if (top == null)
{
top = new StackElement<T>(item);
}
else
{
temp = top;
top = new StackElement<T>(item);
top.Below = temp;
}
}
public T Pop()
{
if (top == null)
{
throw new Exception("Sorry, nothing on the stack");
}
else
{
T temp = top.Data;
top = top.Below;
return temp;
}
}
public void Clear()
{
while (top != null)
Pop();
}
}
class TestProgram
{
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
private static void Test1()
{
Stack<string> myStack = new Stack<string>();
myStack.Push("joe");
myStack.Push("mike");
myStack.Push("adam");
if (myStack.Pop() != "adam") { throw new Exception("fail"); }
if (myStack.Pop() != "mike") { throw new Exception("fail"); }
if (myStack.Pop() != "joe") { throw new Exception("fail"); }
}
private static void Test3()
{
Stack<string> myStack = new Stack<string>();
myStack.Push("joe");
myStack.Push("mike");
myStack.Push("adam");
myStack.Clear();
try
{
myStack.Pop();
}
catch (Exception ex)
{
return;
}
throw new Exception("fail");
}
private static void Test2()
{
Stack<string> myStack = new Stack<string>();
myStack.Push("joe");
myStack.Push("mike");
myStack.Push("adam");
if (myStack.Pop() != "adam") { throw new Exception("fail"); }
myStack.Push("alien");
myStack.Push("nation");
if (myStack.Pop() != "nation") { throw new Exception("fail"); }
if (myStack.Pop() != "alien") { throw new Exception("fail"); }
}
}
}
I think the Clear() method could be sped up significantly by changing it to top = null;. The entire stack will be garbage collected, and no loop required in the mean time.
You could simply use an array. The .NET array methods are really fast.
public class Stack<T>
{
private const int _defaultSize = 4;
private const int _growthMultiplier = 2;
private T[] _elements;
private int _index;
private int _limit;
public Stack()
{
_elements = new T[_defaultSize];
_index = -1;
_limit = _elements.Length - 1;
}
public void Push(T item)
{
if (_index == _limit)
{
var temp = _elements;
_elements = new T[_elements.Length * _growthMultiplier];
_limit = _elements.Length - 1;
Array.Copy(temp, _elements, temp.Length);
}
_elements[++_index] = item;
}
public T Pop()
{
if (_index < 0)
throw new InvalidOperationException();
var item = _elements[_index];
_elements[_index--] = default(T);
return item;
}
public void Clear()
{
_index = -1;
Array.Clear(_elements, 0, _elements.Length);
}
}
Might be preferable to use dynamic array as the data structure instead of a linked list. The array will have better locality of reference because the elements are next to each other. A stack doesn't need ability to delete elements in the middle, splicing etc. so an array suffices.