level order queue implemmentation in C - c

I understand the logic of using a queue to visit the nodes in a binary search tree level by level.
However i tried to implemment in C but i'am stuck because i don't know how to enqueue them properly. Starting with the root i can create a Queue but after that if i add the children of the root to the queue i will lose the children of those new nodes since iam modifying the connections in the Queue every time a add a new node.
I could create a new data type that has one more link to use in the linked list Queue, that should work. What is the best approach here?

visit[ing] the nodes in a binary search tree level by level
has a name: it is called a "breadth-first" traversal of the tree. Starting with an empty queue, you enqueue the root node and then repeatedly dequeue the first node in the queue, process it somehow, and enqueue all that node's children, until there are no more nodes enqueued. When exactly you should enqueue a node's children relative to other processing of that node may depend on exactly what processing you intend to perform, especially if it involves structurally modifying the tree.
As long as the per-node processing can affect only the subtree rooted at the then-current node, this is all fine. If you need to be able to affect other parts of the overall tree, however, then a breadth-first traversal probably is not appropriate for your task.
You said
[I] don't know how to enqueue them properly. Starting with the root [I] can create a Queue but after that if [I] add the children of the root to the queue [I] will lose the children of those new nodes since [I] am modifying the connections in the Queue every time a add a new node.
The key concept here is that membership and position in the queue are separate and independent from membership and position in the tree. You could manage that by adding additional links to the node structures themselves, or by creating a new structure for the queue elements that contains a pointer to the enqueued BST node. The latter decouples the tree from the queue, which many, including me, would consider preferable for most purposes.

Related

Linked List sentinel node to avoid reassigning pointer to first node

Theory
When deleting a node from a linked list, pointers to the first node in the list will need to be updated if the node being deleted from the list is the first one.
Background
Libevent: how to close all open sockets on shutdown?
Situation
In my server application, a pointer to the first node in a linked list of socket connections is held in a struct holding data related to the context of the running instance, such as listening socket port and so on. When a connection is closed, the related node in the linked list must be removed which means that the function which deletes the node must also access to the instance context struct.
My first ideas were:
Each connection node in the linked list has a pointer to the instance context struct. (Messy.)
Global variable pointer to instance context struct. (Evil.)
Then I had the idea to make the first node in the linked list a sentinel node thereby avoiding the possibility that the first node would ever be removed and therefore side-stepping the need for the socket close function to have access to the instance context.
Question
Is this a suitable use of sentinel nodes or is there a better way to solve this problem?
Is there any meta data about the linked list you'd like to store such as the length of the list? If so, you can store them in the sentinel node.

Rush hour - Iterative Deepening

I have to solve the "rush hour puzzle" by iterative deepening algorithm. I have read a lot of topics here on stackoverflow and also on the internet. I think that I understand the iterative deepening algorithm. Basically you just go deeper into the tree and try to find the solution.
I figured that I need to create a graph or a tree from the puzzle, but I really don't have an idea how. Also, if I would have the tree, then how would I tell if something is a valid move or a final state?
There were answers that the nodes should be possible moves and the edges are between the nodes that can be reached in one move. I can imagine this, but somehow I'm getting trouble in see how this can be useful or better yet how can this solve the problem.
Please help me, I'm not asking for complete solution or code sample, I just need some easy explanation of the problem.
There is a reason you need to use the deepening algorithm. Imagine you name each car A, B, C, D... The root node of your tree is the initial board state. Now, move car A. You go down one node in the tree. Move car A back. You are at the initial state, but you made two moves to get here, so you are two nodes down the tree. Repeat over and over. You will never hit a final state.
The root node of your tree is the initial board state. Given that node, add a child node to it for every possible valid move. So, each child node will be what the initial tree looks like after one move. Now, for each of those child nodes, do the same thing: make a child node where each node is one move off the original child node.
Eventually, you will hit a solution to the puzzle. When that happens, you print the moves from the root node to the solution child node and quit. This algorithm ensures that you find a solution with the least number of moves.

In a tree data structure, display tree nodes level by level

Question: how can we display tree nodes level by level ?. could you please give me time and space efficient solution .
Example :
A
/ \
B C
/ \ / \
D E F G
void PrintTree(struct tree *root);
Output:
You have to print tree nodes level by level
A
B C
D E F G
If you're feeling brutish, and want to think very simply about the level you are at...
You will need:
Two queues
A slight twist on Jack's approach
So, start with root.
Tack its children onto the first queue.
Step through them, tacking their children onto the second queue as you go.
Switch to the second queue, step through, pushing their children onto the first queue.
Wax on, wax off.
Really it's just a slight expansion of the same idea, the breadth first search or sweep, which is worth thinking about as a pattern, since it applies to a variety of data structures. Almost anything that's a tree or trie, and a few things that aren't, in fact!
To save space and time on SO:
http://thecodecracker.com/c-programming/bfs-and-dfs/
This kind of visit is called Breadth-first or Level Order. You can see additional infos here.
Basically you
first visit the current node
then all the children of that node
then all the children of every children and so on
This should be achieved easily with a FIFO structure:
push the root
until queue is empty
take first element, visit it, and push all its children to the end of the queue
repeat

Why exactly do we need a "Circular Linked List" (singly or doubly) data structure?

Why exactly do we need a "Circular Linked List" (singly or doubly) data structure?
What problem does it solve that is evident with simple Linked Lists (singly or doubly)?
A simple example is keeping track of whose turn it is in a multi-player board game. Put all the players in a circular linked list. After a player takes his turn, advance to the next player in the list. This will cause the program to cycle indefinitely among the players.
To traverse a circular linked list, store a pointer to the first element you see. When you see that element again, you have traversed the entire list.
void traverse(CircularList *c) {
if (is_empty(c)) {
return;
}
CircularList start = c;
do {
operateOnNode(c);
c = c->next;
} while(c != start);
}
Two reasons to use them:
1) Some problem domains are inherently circular.
For example, the squares on a Monopoly board can be represented in a circularly linked list, to map to their inherent structure.
2) Some solutions can be mapped to a circularly linked list for efficiency.
For example, a jitter buffer is a type of buffer that takes numbered packets from a network and places them in order, so that (for example) a video or audio player can play them in order. Packets that are too slow (laggy) are discarded.
This can be represented in a circular buffer, without needing to constantly allocate and deallocate memory, as slots can be re-used once they have been played.
It could be implemented with a linked-list, but there would be constant additions and deletions to the list, rather than replacement to the constants (which are cheaper).
Something i found from google.
A singly linked circular list is a linked list where the last node in thelist points to the first node in the list. A circular list does not contain NULL pointers.
A good example of an application where circular linked list should be used is a timesharing problem solved by the operating system.
In a timesharing environment, the operating system must maintain a list of present users and must alternately allow each user to use a small slice of CPU time, one user at a time. The operating system will pick a user, let him/her use a small amount of CPU time and then move on to the next user, etc.
For this application, there should be no NULL pointers unless there is absolutely no one requesting CPU time.
Applications
1) We can use circular linked list any application where the entries appear in a rotating manner.
2) Circular linked list is the basic idea of round robin scheduling algorithm.
A circular linked list can be effectively used to create a queue (FIFO) or a deque (efficient insert and remove from front and back). See http://en.wikipedia.org/wiki/Linked_list#Circularly-linked_vs._linearly-linked
Circular linked lists are widely used in applications where tasks are to be repeated or in time sharing applications. Circular queue can keep a track of tasks which have been performed and which has to be performed,once the specific task is done it jumps to next one and when whole set of task is conpleted it again jumps to first task to complete the remaining job.
In practical use : when you open multiple applications on your system the memory of those applications are saved in a circular fashion, you can observe this if u continuously press win+tab/alt+tab for switching applications.
Also in multiplayer board games ,each player are assigned to node in the linked list and the rotation is performed
Circular linked lists (singly or doubly) are useful for applications that need to visit each node equally and the lists could grow. If the size of the list if fixed, it is much more efficient (speed and memory) to use circular queue.
A circular list is simpler than a normal doubly-linked list. Append is just prepend and shift forward once, Pop back is just shift back once and pop front. By tying the two ends together, you get a double-ended list for the cost of just implementing the operations of a one-ended list.
We can use circularly linked list in resource pooling. If many users want to use a shared resource, we can allocate that resource using circularly linked list.
A good example of an application where circular linked list should be used is a timesharing problem solved by the operating system.

please can some one help me explain linked list?

I have tried a lot to learn linked list.But all my efforts were wasted.Please can some one help me understand linked list by providing his/her own code?Thanks in advance.
A linked list is simply a list of elements (usually called nodes) where each node has a reference (or pointers, in C) to the next node:
http://img837.imageshack.us/img837/5613/ll1s.png
You keep track of the list by having a pointer to the first node (the "head"), and by having the last node point to null
Linked lists where each element points to both the next and previous nodes are called doubly-linked lists.
By following these references, you can traverse the list and get any node.
A common advantage of linked lists over arrays is that you can insert and remove the elements in O(1) (constant) time. The disadvantage is that you have O(N) random-access.
See Wikipedia for more.
Have you play some of these rally games? The organizer left this hints all around the city and you must get one hint and then solve the riddle for getting the position of the next hint. Now, imagine every hint comes with a little prize.
Well, linked list are like that: every element has "content" on it AND the memory address (the hint) for getting the next item. The next item, of course, has another prize and another hint.
A linked list is a series of object each pointing to the next one in the list. The last element in the list has NULL as it's next pointer.
You keep track of the head of the list in your program so you can traverse the list from the start.
You might want to keep track of the current position in the list, but that will depend on your application.
A doubly linked list has a previous element pointer too enabling you to traverse the list in both directions.
This:
typedef struct tagProp
{
rtPropertyKey key;
rtProperty property;
struct tagProp *next;
} TProperty;
defines a property key/value lookup list.
A linked list is implemented as a list of "nodes". The nodes are linked together using pointers. The following code describes one node. The pointer to the next node is called next. In my example, each node contains an integer value as its data.
struct node {
int val;
struct node * next;
};
The fun is how to actually create a list. You have to use malloc to create new nodes. When you malloc the new node, you have to tie into the list using the next pointer.
We can help you more if you specifically tell us what your issues are...

Resources