Trying to implement linkedlist - c#

public void Push(Node newNode)
{
while (true)
{
Node tmp = this.head;
newNode.next = tmp;
if (Interlocked.CompareExchange(ref this.head, newNode, tmp) == tmp)
{
break;
}
}
}
public Node Pop()
{
Node pop=null;
while (this.head != null)
{
pop = this.head;
var oldcount = this.popcount;
var newcount = oldcount + 1;
if (Interlocked.CompareExchange(ref this.popcount, newcount, oldcount) == oldcount)
{
pop = Interlocked.CompareExchange(ref head, head.next, head);
break;
}
pop = null;
}
return pop;
}
//---------------------------------------------------------
while (count < 10000) // 4 thread run this code
{
for (int i = 0; i < 2; i++)
{
Node temp;
if (freelist.head != null)
{
temp = freelist.Pop();
headlist.Push(temp);
}
}
for (int j = 0; j < 1; j++)
{
Node temp;
if (headlist.head != null)
{
temp = headlist.Pop();
freelist.Push(temp);
}
}
count++;
Console.WriteLine(count);
}
I'm trying to implement lock free linkedlist.
I add popcount to avoid aba problem.
And I implement Push and Pop using CAS.
When I run this code, It is not working as I think.
class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
}
}
When I run code, a Node.next points itself.
For example, Node.data = 99720 and Node.next = Node So, When I go to Node.next It is still 99720 Node.
Can't figure out why it happen...

It looks like you are trying to build a lock-free stack. I'm not sure what (pseudo-) code you used as basis for your implementation, but your attempt to solve the ABA problem with popcount cannot work. When you are using a version tag to prevent ABA, it has to be combined with the pointer, i.e., the pointer and the tag have to be updated in a single atomic operation. Java provides AtomicStampedReference for exactly this purpose, but unfortunately .NET does not provide anything similar.
However, since you are working with .NET you have the luxury of a garbage collector, so you don't really need to worry about the ABA problem as long as you don't reuse your nodes.
BTW: your pop function is missing a loop.

Related

Elements are not inserting properly while creating a linked list in c#

I have the node structure like this for singly-linked list.
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
I am trying to create a liked list like this
//requiredDigit = 123456
ListNode finalNode = new ListNode();
for(int i=0; i < requiredDigit.Length; i++){
finalNode.val = requiredDigit[i] - '0';
finalNode.next = new ListNode();
}
Whenever I try this kind of approach the list is being created as 60, the first element is being missed.
The issue here is that you're not moving to the next node in the linked list chain. Currently your solution doesn't change the value of finalNode; it stays on the same instance and nothing progresses, so you end up just overriding the starting node. the val value goes from 1 to 2 to 3, etc, but all in the same node.
This is a potential solution. I'm sure there's a more elegant one, but this works:
ListNode startNode = null, finalNode = null, iterNode;
for(int i=0; i < requiredDigit.Length; i++)
{
if (startNode == null)
{
startNode = new ListNode(requiredDigit[i] - '0');
finalNode = head;
}
else if (finalNode.next == null)
{
finalNode.next = new ListNode(requiredDigit[i] - '0');
finalNode = finalNode.next;
}
}

Iterative Deepening Search in C#

I am trying to implement Iterative Deeping Search. I do not know what I am doing wrong, but I don't seem to be getting it right. I always end up with an infinite loop.
Can anyone point out my mistake?
I implemented the Depth-Limited Search and used it in my IDS code. DLS seems to be working fine on its own, but I do not understand IDS and why i'm ending up in an infinite loop.
public class IterativeDeepeningSearch<T> where T : IComparable
{
string closed;
public int maximumDepth;
public int depth = 0;
bool Found = false;
Stack<Vertex<T>> open;
public IterativeDeepeningSearch()
{
open = new Stack<Vertex<T>>();
}
public bool IDS(Vertex<T> startNode, Vertex<T> goalNode)
{
// loops through until a goal node is found
for (int _depth = 0; _depth < Int32.MaxValue; _depth++)
{
bool found = DLS(startNode, goalNode, _depth);
if (found)
{
return true;
}
}
// this will never be reached as it
// loops forever until goal is found
return false;
}
public bool DLS(Vertex<T> startNode, Vertex<T> goalNode, int _maximumDepth)
{
maximumDepth = _maximumDepth;
open.Push(startNode);
while (open.Count > 0 && depth < maximumDepth)
{
Vertex<T> node = open.Pop();
closed = closed + " " + node.Data.ToString();
if (node.Data.ToString() == goalNode.Data.ToString())
{
Debug.Write("Success");
Found = true;
break;
}
List<Vertex<T>> neighbours = node.Neighbors;
depth++;
if (neighbours != null)
{
foreach (Vertex<T> neighbour in neighbours)
{
if (!closed.Contains(neighbour.ToString()))
open.Push(neighbour);
}
Debug.Write("Failure");
}
}
Console.WriteLine(closed);
return Found;
}
}
}
PS: My Vertex Class just has two properties, Data and Children
The for loop iterates on _depth but in the DLS function you are passing depth, which is always 0
for (int _depth = 0; _depth < Int32.MaxValue; _depth++)
{
bool found = DLS(startNode, goalNode, depth);
if (found)
{
return true;
}
}

Why Class instance overwrites another instance

I've an issue to ask you guys.
I have a class shown below:
public class Node
{
public int Kova1; // Kova 1
public int Kova2; // Kova 2
public int Kova3; // Kova 3
public int ActionNo; // Yapılan İşlem
public Node(int kova1, int kova2, int kova3, int actionNumber)
{
Kova1 = kova1;
Kova2 = kova2;
Kova3 = kova3;
ActionNo = actionNumber;
}
public Node(int kova1, int kova2, int kova3)
{
Kova1 = kova1;
Kova2 = kova2;
Kova3 = kova3;
}
public Node()
{
}
public Node AnneNode;
}
And these functions:
public void CocukNodeOlustur(LinkedList<Node> Acik, LinkedList<Node> Kapali, Node temp)
{
Node cocukState;
Node temp2 = temp;
for (int i = 0; i < 12; i++)
{
cocukState = YeniStateOlustur(temp, i);
if ((ActionKontrol(cocukState)) && (GoalBulundu(Acik, Kapali, cocukState)) &&
((cocukState.Kova1 != temp2.Kova1) && (cocukState.Kova2 != temp2.Kova2) && (cocukState.Kova3 != temp2.Kova3)))
{
cocukState.AnneNode = temp;
Acik.AddFirst(temp);
}
}
}
public Node YeniStateOlustur(Node s, int j)
{
int tempKova1, tempKova2, tempKova3;
Node yeniCocuk = new Node();
yeniCocuk = s;
yeniCocuk.ActionNo = j;
// Gelen numaraya göre uygulanan işlemin seçimi yapılıyor.
switch (j)
{
case 0:
{
yeniCocuk.Kova1 += (3 - yeniCocuk.Kova1);
yeniCocuk.Kova2 += 0;
yeniCocuk.Kova3 += 0;
}
break;
case 1:
{
yeniCocuk.Kova1 += 0;
yeniCocuk.Kova2 += (5 - yeniCocuk.Kova2);
yeniCocuk.Kova3 += 0;
}
break;
}
return yeniCocuk;
}
In the main function
Node temp = new Node();
while (!(Acik.Count == 0))
{
p.CocukNodeOlustur(Acik, Kapali, temp);
Kapali.AddLast(temp);
}
So When I debug my program, I see that Whenever the code jumps to the YeniStateOlustur() function, all the Node instance's in program is affected by the changes in YeniStateOlustur(). It seems the instance in the function overwrite all instances of Node class.
I don't understand why it happens?
How can I overcome this?
My best regards and sory for the long post.
The problem is that all of the nodes are the same instance. Your sample code includes "new Node()" only twice, and in the second case (inside the method YeniStateOlustur), the new instance is immediately discarded. That function therefore returns the same node that was passed to it:
public Node YeniStateOlustur(Node s, int j)
{
int tempKova1, tempKova2, tempKova3;
Node yeniCocuk = new Node();
yeniCocuk = s;
//...
return yeniCocuk;
}
In the method CocukNodeOlustur, all node variables point to the same Node:
public void CocukNodeOlustur(LinkedList<Node> Acik, LinkedList<Node> Kapali, Node temp)
{
// here, temp == temp
Node cocukState;
// now, temp == temp and cocukState is uninitialized.
Node temp2 = temp;
// now, temp == temp, temp2 == temp, and cocukState is uninitialized.
for (int i = 0; i < 12; i++)
{
cocukState = YeniStateOlustur(temp, i);
// now, temp == temp, temp2 == temp, and cocukState == temp
if ((ActionKontrol(cocukState)) && (GoalBulundu(Acik, Kapali, cocukState)) &&
((cocukState.Kova1 != temp2.Kova1) && (cocukState.Kova2 != temp2.Kova2) && (cocukState.Kova3 != temp2.Kova3)))
{
cocukState.AnneNode = temp;
Acik.AddFirst(temp);
}
}
}
Your code seems to assume that Node is a value type (struct), but it is obviously a reference type (class). If you're unsure about the difference, you should take a step back and do some reading and experimentation.
A quick fix might be to change the declaration of Node to a struct, but I would recommend against that. Programming with structs can be very tricky, and that would be especially true if your understanding of the differences between structs and classes is shaky.

How to find height of BST iteratively?

public void HeightIterative()
{
int counter = 0;
int counter2 = 0;
TreeNode current=root;
if(current != null)
{
while(current.LeftNode!=null)
{
counter++;
current = current.LeftNode;
}
while(current.RightNode!=null)
{
counter2++;
current = current.RightNode;
}
}
int res = 1+Math.Max(counter, counter2);
Console.WriteLine("The Height Of Tree Is: "+res);
}
I wrote iterative method, to calculate height of tree. but in some cases its not working properly. As in case:
10
1
2
3
4
5
18
17
16
15
14
13
what's the problem. according to this sequence height of tree is 6 where as my code is showing 5.
You are using two loops, but each loop investigated only oneside of node, but each node in tree has two sides you should investigate it all. You can do it through recursion call.
private int GetLen(TreeNode node)
{
var result = 0;
if(node != null)
{
result = Math.Max(GetLen(node.LeftNode), GetLen(node.RightNode)) + 1;
}
return result;
}
public void HeightIterative()
{
int res = GetLen(root);
Console.WriteLine("The Height Of Tree Is: "+res);
}
Iterative version:
private class NodeInfo
{
public NodeInfo(TreeNode node, int len)
{
Node = node;
Len = len;
}
public TreeNode Node {get; private set;}
public int Len {get; private set;}
}
public void HeightIterative()
{
int maxLen = 0;
var queue = new Queue<NodeInfo>();
queue.Enqueue(new NodeInfo(root, 1));
while (queue.Count > 0)
{
var item = queue.Dequeue();
var current = item.Node;
var currentLen = item.Len;
if (current.LeftNode != null)
{
queue.Enqueue(new NodeInfo(current.LeftNode, currentLen + 1));
}
if (current.RightNode != null)
{
queue.Enqueue(new NodeInfo(current.RightNode, currentLen + 1));
}
if (currentLen > maxLen)
{
maxLen = currentLen;
}
}
Console.WriteLine("The Height Of Tree Is: " + maxLen);
}
There is a way that does not require any extra space except the queue for storing the nodes.
Add child nodes of a current element and remember size of the queue.
Let each dequeue call decrement the counter
When counter reaches zero that means we are done with current level.
Repeat and count number of times counter reaches zero - this is the depth/height of the tree
Code goes like this :
public int treeDepth(Node root){
int height = 0;
int counterNodesInLevel = 1;
if(root!=null)
{
Queue<Node> queue=new Queue<Node>()
queue.enqueue(root);
while (!queue.isEmpty()){
Node current = queue.dequeue();
counterNodesInLevel -= 1;
if(current.left!=null){
queue.enqueue(current.left)
}
if(current.right!=null){
queue.enqueue(current.right)
}
if (counterNodesInLevel == 0){
height += 1;
counterNodesInLevel = queue.Size();
}
}
}
return height;
}
Time complexity is O(N), space complexity is O(N)
The problem:
You are finding the depth of the left-most node in the first loop, and the right-most in the second, and never interrogating any node that involves going down to the left AND the right.
A solution:
Have a single loop that drills down the left nodes, but adds each right node that it 'skips' into a queue. When you run out of left nodes, pop-off a node form your queue and continue on until the queue becomes empty. You'll need to store the height of each node you put in the queue with that node.
public int Height()
{
int result = GetMaxHeight(this.Root,0);
return result;
}
private int GetMaxHeight(Node<T> node,int count)
{
int leftMax = 0, rightMax = 0;
if (node.Left != null)
{
leftMax = GetMaxHeight(node.Left, count+1);
}
if (node.Right != null)
{
rightMax = GetMaxHeight(node.Right, count + 1);
}
if(node.Left==null && node.Right == null)
{
return count;
}
return Math.Max(leftMax,rightMax);
}

How to improve compare of item in sorted List<MyItem> with item before and after current item?

Does anyone know about a good way to accomplish this task?
Currently i'm doing it more ore less this way, but i'm feeling someway unhappy with this code, unable to say what i could immediately improve.
So if anyone has a smarter way of doing this job i would be happy to know.
private bool Check(List<MyItem> list)
{
bool result = true;
//MyItem implements IComparable<MyItem>
list.Sort();
for (int pos = 0; pos < list.Count - 1; pos++)
{
bool previousCheckOk = true;
if (pos != 0)
{
if (!CheckCollisionWithPrevious(pos))
{
MarkAsFailed(pos);
result = false;
previousCheckOk = false;
}
else
{
MarkAsGood(pos);
}
}
if (previousCheckOk && pos != list.Count - 1)
{
if (!CheckCollisionWithFollowing(pos))
{
MarkAsFailed(pos);
result = false;
}
else
{
MarkAsGood(pos);
}
}
}
return result;
}
private bool CheckCollisionWithPrevious(int pos)
{
bool checkOk = false;
var previousItem = _Item[pos - 1];
// Doing some checks ...
return checkOk;
}
private bool CheckCollisionWithFollowing(int pos)
{
bool checkOk = false;
var followingItem = _Item[pos + 1];
// Doing some checks ...
return checkOk;
}
Update
After reading the answer from Aaronaught and a little weekend to refill full mind power i came up with the following solution, that looks far better now (and nearly the same i got from Aaronaught):
public bool Check(DataGridView dataGridView)
{
bool result = true;
_Items.Sort();
for (int pos = 1; pos < _Items.Count; pos++)
{
var previousItem = _Items[pos - 1];
var currentItem = _Items[pos];
if (previousItem.CollidesWith(currentItem))
{
dataGridView.Rows[pos].ErrorText = "Offset collides with item named " + previousItem.Label;
result = false;
sb.AppendLine("Line " + pos);
}
}
dataGridView.Refresh();
return result;
}
It's certainly possible to reduce the repetition:
private bool Check(List<MyItem> list)
{
list.Sort();
for (int pos = 1; pos < list.Count; pos++)
{
if (!CheckCollisionWithPrevious(list, pos))
{
MarkAsFailed();
return false;
}
MarkAsGood();
}
return true;
}
private bool CheckCollisionWithPrevious(List<MyItem> list, int pos)
{
bool checkOk = false;
var previousItem = list[pos - 1];
// Doing some checks ...
return checkOk;
}
Assuming that CheckCollisionWithPrevious and CheckCollisionWithFollowing perform essentially the same comparisons, then this will perform the same function with a lot less code.
I've also added the list as a parameter to the second function; it doesn't make sense to be taking it as a parameter in the first function, but then referencing a hard-coded member in the function it calls. If you're going to take a parameter, then pass that parameter down the chain.
As far as performance is concerned, though, you're re-sorting the list every time this happens; if it happens often enough, you might be better off using a sorted collection to begin with.
Edit: And just for good measure, if the whole point of this code is just to check for some kind of duplicate key, then you would be way better off using a data structure that prevents this in the first place, such as a Dictionary<TKey, TValue>.

Categories