I want to use an empty stack S to check whether a Queue Q contaitns element x, thus my solution was to copy elements of Q into S and check if contain x, but I'm also asked to return S elements into Q again as it was originaly, this must be done using only a Q and S without any other arrays of SL, so I have written this algorithm:
Boolean found ← false
int element ← 0
While(Q is not empty)
element ← Q.dequeue()
if(element equal x)
found ← true
S.push(element)
While(S is not empty)
( elements back to Q) ?
stuck in last step, if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed
Correct, the order will be reversed.
This means that if you repeat the algorithm yet again (all to S and back to Q) you will reverse it yet again, meaning you will get back to the original order of elements, which is what you want.
if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed
That's right, it will be reversed. You can use it to your advantage by observing that once you run the same loop again, you would get the original order back.
You can avoid writing the same loop twice if you make a method that does the search, and leaves the queue in reversed state. You can call your search method twice, and ignore the second return value.
This feels like a HW question so I won't solve it for you, but I will give you a hint - what happens when you dequeue a queue into a stack and then dequeue the stack back to the queue?
How can you use that phenomena to restore the original queue?
I am not sure how java default Queue work.
Remove element from the end of the queue.
Check if that element is x, if so return true.
Else, push it into the stack
Repeat until you find x or all the Queue is empty.
When you are done, pop elements one by one from the stack and add them at the beginning of the queue everytime, the last element in the stack would become the first element in the queue. Thus you maintain the order.
Related
I really need your help for me to understand recursion properly. I can understand basic recursions and their logic like fibonacci
int factorial(int n)
if(n <=1)
return n
else
return(n*factorial(n-1))
That's easy the function keep calling factorial until n becomes zero and finally multiply all the results. But recursions like tree traversal is hard for me to understand
void inorderTraverse(Node* head)
if(head!=NULL){
inorderTraverse(head->left)
cout << head-> data
inorderTraverse(head->right)
}
}
Here I lost the logic how does this function goes if first recursion call will go back to function how can it goes to cout line or how can it show right child data. I really need your help.
Thank you
A binary search tree in alphabetical order:
B
/ \
A C
inorderTraverse(&A) will first descend to A and print it (recursively printing any subtree), then print B, then descend to C and print it (recursively printing any subtree).
So in this case, A B C.
For a more complicated tree:
D
/ \
B E
/ \
A C
This will be printed as A B C D E. Notice how the original tree is on the left of D, so is printed in its entirety first; the problem is reduced to a smaller instance of the starting problem. This is the essence of recursion. Next D is printed, then everything on the right of D (which is just E).
Note that in this implementation, the nodes don't know about their parent. The recursion means this information is stored on the call stack. You could replace the whole thing with an iterative implementation, but you would need some stack-like data structure to keep track of moving back up through the tree.
Inorder traversal says you need to traverse as Left-Root-Right.So for one level it is fine we print in left-root-right format. But With the level increases you need to makesure your algorithm traverse in the same way.So you need to print the leftSubtree first then the root of that subTree and then the right subTree at each level.
The Recursive code inorderTraverse(head->left) tells till the node is not null go to its leftside of the tree.Once it reaches the end it prints the left node then print the Root node of that subTree and wahtever operation u performed on leftSubTree you need to perform the same on Right subTree that's why you write inorderTraverse(head->right). Start debugging by creating 3level trees. Happy Learning.
Try to imagine binary tree and then start traversing it from root. You always go left. If there is no more lefts then you go right and after that you just go up. And you will finish back in root (from right side).
It is similar as going thought maze. You can choose that you will always go to left. (you will always touch left wall). At the end you will finish in exit or back in entrance if there isn't another exit.
In this code is important that you have two recursive calls in body. First is for left subtree and second is for right subtree. When you finish one function returns you back to node where you started.
Binary search trees have the property that for every node, the left subtree contains values that are smaller than the current node's value, and the right subtree contains values that are larger.
Thus, for a given node to yield the values in its subtree in-order the function needs to:
Handle the values less than the current value;
Handle its value;
Handle the values greater than the current value.
If you think of your function initially as a black box that deals with a subtree, then the recursion magically appears
Apply the function to the left subtree;
Deal with the current value;
Apply the function to the right subtree.
Basically, the trick is to initially think of the function as a shorthand way to invoke an operation, without worrying about how it might be accomplished. When you think of it abstractly like that, and you note that the current problem's solution can be achieved by applying that same functionality to a subset of the current problem, you have a recursion.
Similarly, post-order traversal boils down to:
Deal with all my children (left subtree, then right subtree, or vice-versa if you're feeling contrary);
Now I can deal with myself.
Suppose I have a list(0,1,2,3,4,5,6)
I already have my queueclass.
I want the result as 1,3,5,0,2,4,6 (the item at nth position is attached to the end of the original queue.
Here is what I have so far:
Queue a=new Queue();
for(int i=0;i<7;i++){
a.enter(i);
}
Queue temp=new Queue();`
while(!a.isEmpty()){
temp.enter(a.leave());//put the first element in temp
System.out.print(a.leave()+" ");//print out the second one
a.enter(temp.leave());//put the first element at the end of original queue
}
So My idea is to store the item that leave in temp then enter back.
No matter how I try this, it cannot give me the correct result. And its a infinite loop.
leave() remove the first item and return it.
enter() put the element at the end of queue
OK I've solved the problem.
I should do like:
while(!a.isEmpty()){
a.enter(a.leave());
System.out.print(a.leave()+" ");
}
Then it will give me the correct result.
Thanks guys for the effort, and sorry if anything in this problem is unclear. I'm still new to this :)
I will start by warning you that this is a lousy answer that does not actually solve your problem, because I can't figure out what your goal is. It does, however, explain the infinite loop you've encountered.
The infinite loop is the while, which waits for Queue a to be empty, which will never happen (unless a was already empty when the while loop started).
Each iteration through your while loop de-queues two items from a, and then en-queues the first item. Even if this is what you intended for most of the iterations (I honestly can't tell), it fails for what should have been the last one.
When a is down to just one element, your while loop starts repeating this useless behavior forever:
Remove the one and only element from Queue a.
Remove another element from the now-empty a... somehow.
Print God-knows-what, followed by a space.
Put that "one and only" element (the one that actually existed) right back onto a.
Test if a is empty, which --- surprise --- it is not.
Go to 1.
Heat-Death of the Universe.
Once Queue a gets caught in this trap, it will "always" contain that last element. The brief moments during which it is empty will occur only in the middle of the while block, and never during the iteration test at the top of that same block.
Other Weirdness
I came up with these questions while typing this answer. They are questions you should ask yourself:
What is the goal of your program? (This will be required for almost any Stack Overflow questions you ask in the future. Its near-absence from this question is why you've received such an incomplete answer.)
What happens when you call leave on an empty Queue? (Your while loop does this forever.) Why is that the obviously correct thing to do? What are the alternatives, and why are they obviously incorrect?
What is Queue temp for? It never has more than one item in it, so why can't it be replaced with a local variable?
Why do you print the items you throw away? Alternatively: Why do you throw away the items you print? Is printing them to the console something you wanted to do at all?
What does any of this have to do with the "Nth position" in your title?
For future questions, I suggest you review the Help Center's "How do I ask a good question?" and the links at the bottom of that article, especially Eric Lippert's "How To Debug Small Programs". I suspect your code could benefit a lot from the latter's "Rubber Duck Debugging":
Explain to the duck using simple words why each line of each method in your program is obviously correct. At some point you will be unable to do so, either because you don't understand the method you wrote, or because it's wrong, or both. Concentrate your efforts on that method; that's probably where the bug is.
The duck would have caught many of these, I think.
the methods used in the program doesn't exist i believe i.e .leave()
but to get the element from any position using queues then you can use this
here n is the required position-1
for example if you need to print out element which is at position 5
n = 5-1, i.e 4
cause it follows indexing.
for(int i = 0; i<n; i++) {
queue.remove();
}
System.out.print(queue.peek());
I would like to make something where the strings will move up in an orderly fashion. For example:
Iteration 1:
Hello There
I am
Asking a question
To you
Iteration 2:
I am
Asking a question
To you
Next String
How exactly would I go about this, in the least memory-intensive way? Thanks.
An easy way is a circular queue.
A circular queue can be implemented as an array and a pointer to the first index. When you want to change the first element, you need only advance the index. When the index passes the end of the array, it rolls back to index 0.
With a circular queue:
Moving up the strings does not require moving anything in the array.
All the entries in the queue can be stored in an array, which requires less memory than a linked implementation.
If you're not obliged to use an array i would suggest a queue, with it its fairly simple to implement what you wanna do.
Queue<String> foo = new Queue<String>();
foo.offer("Hello"); //first element is hello
foo.offer("world"); //second element is world
String s = foo.poll(); //s = hello and now the first element of the queue is world
I was looking through the LinkedList API for Java 7 and noticed something curious. there does not appear to be a "remove before (or after)" type of method. For example, If I have a 100 element LinkedList, and I want to remove the first 20 elements, Java seems to force you to remove them one at a time, rather than moving the start pointer to the 21st element and deleting the link between 20 and 21. It seems like this is an operation that can be done in O(1) time, instead of O(n) time as Java seems to force you to do it.
Am I missing something here, or is it just a glaring hole in Java?
EDIT
I am aware of the sublist(int, int) method in the List interface. I still think that this will be slightly less efficient than the generic "chop off the first (or last) n" use case.
EDIT 2
Touche to everyone who pointed out that finding the nth element is not O(1). Regardless of the ease of chopping off the first n-1 elements, it still takes O(n) time to find the nth.
However, as Dilum Ranatunga points out, there is the possibility that an iterator already exists at the given position. In this case, it would still be useful to say "I am here, remove all before me".
It's still an O(n) operation no matter what you do.
You don't have direct access to the individual nodes of the linked list, so you would have to traverse the list first to get access to the 21st node. Once you were there it would be O(1) to 're-head' the list, but it's still O(n) for the entire, atomic operation.
LinkedList inherits a sublist method from List interface. Information can be found here http://docs.oracle.com/javase/6/docs/api/java/util/List.html#subList(int, int)
It is impossible to immediately jump to the Nth element because each prior node contains the address of the Node.next (the next node in the chain). So it has to naturally traverse 20 elements causing O(n) runtime.
For example:
[Node 1, address of Node 2] -> [Node 2, address of node 3] -> etc... -> [Node 20, address of Node 21]
You cannot get the "address of Node 21" without getting to the Node 20 first, and to do so you need to "address of Node 20" from Node 19 and so on.
What is your algorithm for finding item n in O(1) time? This would still be an O(n) operation to locate the nth item and set it as the head. You would save some intermediate pointer assignments compared to 20 removes, but not a huge gain.
You can call list = list.subList(21, list.size()) to get a sublist from 21 to the end of the list.
The operation is O(1), but you do not get a LinkedList back, you get an AbstractList.SubList which acts like a wrapper class for the original LinkedList, delegating methods with the sublist's offsets.
Although this is constant time, it is important to note this is not a new list. If your list size went from n to m, subsequent linear-time methods called on the list will still run in O(n) not in O(m).
Java's java.util.List defines the API listIterator(). ListIterator has previous().
So the idiom you want is:
// some loop construct {
listIter.previous();
listIter.remove();
}
I am looking for something like a Queue that would allow me to put elements at the end of the queue and pop them out in the beginning, like a regular Queue does.
The difference would be that I also need to compact the Queue from time to time. This is, let's assume I have the following items on my Queue (each character, including the dot, is an item in the Queue):
e d . c . b . a
(this Queue has 8 items)
Then, I'd need for example to remove the last dot, so to get:
e d . c . b a
Is there anything like that in the Java Collection classes? I need to use this for a program I am doing where I can't use anything but Java's classes. I am not allowed to design one for myself. Currently I'm just using a LinkedList, but I thought maybe this would be more like a Queue than a LinkedList.
Thanks
edit:
Basically here is what the project is about:
There is a traffic light that can be either green(and the symbol associated is '-') or red('|'). That traffic light is on the right:
alt text http://img684.imageshack.us/img684/9602/0xfhiliidyxdy43q5mageu0.png
In the beggining, you don't have any cars and the traffic light is green, so our list is represented as:
....... -
Now, on the next iteration, I have a random variable that will tell me wherever there is a car coming or not. If there's a car coming, then we can see it appearing from the left. At each iteration, all cars move one step to the right. If they have any car directly on their right, then they can't move:
a...... - (iteration 1)
.a..... - (iteration 2)
..a.... - (iteration 3)
etc.
Now, what happens is that sometimes the traffic light can turn red('-'). In that case, if you have several cars, then even if they had some distance between them when moving, when they have to stop for the traffic light they will get close:
...b.a. - (iteration n)
....b.a - (iteration n+1)
.....ba - (iteration n+2) here they got close to each other
Now, that is the reason why this works like a Queue, but sometimes I have to take down those dots, when the cars are near the red traffic light.
Keep also in mind that the size of of the street here was 7 characters, but it sometimes grows, so we can't assume this is a fixed length list.
A queue is basically a list of items with a defined behavior, in this case FIFO (First In First Out). You add items at the end, and remove them from the beginning.
Now a queue can be implemented in any way you choose; either with a linked-list or with an Array. I think you're on the right path. A linked list would definitely make it easier.
You'll have O(1) for the add and the remove with your queue (if you maintain a reference to the front and the back), but the worst-case scenario for compacting (removing the dot) would be O(n).
I believe there might be a way to reduce the compact operation to O(1) (if you're only removing one dot at a time) if you use a secondary data structure. What you need is another queue (implemented using another linked-list) that maintains a reference to dots in the first linked list.
So, when you insert (a, ., b, c, ., d) you have a list that looks like:
[pointer to rear] -> [d] -> [.] -> [c] -> [b] -> [.] -> [a] <- [pointer to front]
and you also have a secondary queue (implemented as a linked list) that maintains a reference to the dot:
[pointer to rear] -> [reference to second dot] -> [reference to first dot] <- [pointer to front]
Then, when you need to perform a compact operation, all you have to do is remove the first element from the second queue and retain the reference. So you now have a reference to a dot that is in the middle of the first linked list. You can now easily remove that dot from the first list.
You mentioned in a comment that you need to keep track of the order. A queue by definition is an ordered structure (in the sense that things remain in the order they were inserted). So all you need to do is insert a reference to the dot into the second queue when you insert a dot into the first. That way, order is maintained. So when you pull off a reference to a dot from the second queue, you have a reference to the actual and corresponding dot in the first queue.
The trade-off here for speed is that you need more memory, because you're maintaining a second list of references. Worst-case memory requirement is 2x what you're using now. But that is a decent trade-off to get O(1) vs O(n).
Homework exercises/school projects are always tricky, adding subtle stuff to the requirements that may make someone's brain melt down. Do you have any requirement to include the spaces as part of the queue?
Personally, I wouldn't do that unless explicitly required: it seems simpler to represent your cars as Car, Space pairs, (you can define the pair as a struct, assuming you are allowed to use structs) where space is a numeric value representing the space towards the next car in the vehicle. Then, to compact, you only need to look through the list items: when you find one that has Space > 0, do Space--; return;, and all other cars will have already "advanced", as they keep the space with the ones in front of them. In order to output, make sure to toss out Space dots for each car after (if the stoplight is at the right and the cars come from the left) or before (stoplight at left and cars coming from right) the car itself, and there you go. Also note that the Space of the first car represents the distance to the stoplight itself, since it has no car before it.
If you add to the struct a pointer to the next car (and a null pointer for the last car), you already have a linked list: keep a "global" variable that points to the first car (or null for an empty queue). Since Java doesn't directly supports pointers, turn the struct into a class and use "object references" (which are the same as pointers for all purposes other than C'ish pointer arithmetics), and there you go: only one class, built from scratch. The only thing you'll need to touch from Java's libraries is the standard IO and, maybe, a bit of string manipulation, which is an inherent need derived from having to take input and produce output (some colleges have their own course-specific IO libraries, but that doesn't make a big difference here). To loop through the queue you'd do something like this (assuming the class is named "Node", which is quite generic, and obvious names for the fields):
for(Node pos = First; pos != null; pos = pos.Next) {
/* Do your stuff here, knowing that "pos" points to the "current" item on each iteration. */
}
To add new nodes you probably have to traverse the queue to figure out at which distance from the last will the new car "spawn"; when you do so keep the reference from the last node and make its "next" reference point to the new node:
Node last = First;
int distance = 0;
for(Node pos = First; pos != null; pos=pos.Next) {
distance += pos.Space;
last = pos;
}
last.Next = new Node(the_letter_for_this_car, MaxDistance-distance, null);
Of course, tune the constructor to whatever you have.
Considering that this is a college project, let's take a look at some details: the compact process time becomes O(n) and it's memory usage is O(0) (the process itself doesn't need any "local" variables, other than maybe a pointer to traverse the collection which is independent from the length of the queue.) In addition, the memory usage for the queue itself is guaranteed to be smaller or equal to what it would be representing the spaces as items (it only gets to be equal on the worst scenario, when enough cars are stuck at a red light). So, unless the requirements include something incompatible with this approach, I'd expect this to be what your teachers want: it's reasoned, efficient, and compliant to what you were asked for.
Hope this helps.
I would say that a LinkedList would be the best approach here... as a LinkedList allows you to push/pop from the front/back and allows you to remove an item in the middle of the list.
Obviously, the lookup time sucks, but if you are adding/removing from the front/back of the list more often then looking up, then I'd say stick with the LinkedList.
Maybe a second LinkedList which keeps the dot element ?