public void createList(Node root)
{
Dictionary<int, LinkedList<Node>> track = new Dictionary<int, LinkedList<Node>>();
LinkedList<Node> first = new LinkedList<Node>();
first.AddFirst(root);
track.Add(1, first);
int level = 1;
LinkedList<Node> temp = new LinkedList<Node>();
while (true)
{
LinkedList<Node> lis = new LinkedList<Node>();
if (level == 1)
temp = first;
foreach (Node n in temp)
{
if (n.left!=null)
lis.AddLast(n.left);
if (n.right != null)
lis.AddLast(n.right);
}
level++;
temp=lis;
if (lis.Count > 0)
{
track.Add(level, lis);
}
else
break;
}
}
Hello, in the above program in C# i am adding each level of a Binary tree to separate Linked Lists and then adding every linked list to a dictionary. Can some one please tell me how to iterate the through each linked list in the dictionary? If i have Track<1,<1,2,3,4>>, how do i get to 1,2,3,4? What if I wanted to add to or delete to 1,2,3,4?
Thanks to Ramhound for pointers on the problem, I guess i will have to get the LinkedList object for each key in the Dictionary and then modify the linked list, how do i make sure the change reflects back in the Dictionary is m开发者_如何学Cy next question=> Please let me know if the following makes sense
LinkedListObject= Dictionary[mykey]; //Modify the LL, Add,delete etc myDictionary[myKey] = LinkedListObject; //put it back
I do not believe you can modify the dictionary while looping through it. You would have to keep track of what keys you are going to remove, loop through THAT collection, and remove each key at a time.
There are alternatives to a Dictionary that would allow you to modify it while looping through the contents.
To iterate through the linked lists, get a list of values form the Dictionary.
To get the first linked list just call get(1)
on the dicitionary and it will return a LinkedList<Node>
.
Note, I assume this is test code as this has several problems that would keep it from compiling.
精彩评论