I implemented it as an array with two stacks adjacent to each other, but their tops on the either ends. That is, if top(stack1) is at the beginning of keys, top(stack2) is at the end of keys. Bottom(Stack1) and Bottom(Stack2) should be adjacent, but anywhere between top(Stack1) and top(Stack2). To delete, I am poping from Top(Stack1), and for inserting, I am pushing in Top(stack2). Could somebody pls tell me if it is correct to do it this way?
When I read CLRS, I solved the que this way, and had no way to know that it was ryt or not. But it was asked in today's exam, and everyone later on was discussing the way given officially (here and everywhere else on net), so it seems I am the only one to do it such a way. I really wanna know if this is wrong or right ? Please help
Queues and stacks are abstract data structures which have well defined behaviors and any implementation of these data structures should respect this contract.
Your idea of using a single array to implement two stacks is good. But, the inserts and deletes should happen on both stacks.
For eg. lets say you have this setup
2 3 4 5 6
top(stack1) is 2
bottom(stack1) is 4
top(stack2) is 6
bottom(stack2) is 5
after popping from stack1 3 times you would have reached the bottom of your stack i.e 4 and no longer able to pop anything even though there are two more elements in your QUEUE implementation. So, a few corrections to your implementation is required.
So, if I were to implement two stacks which emulate a QUEUE, this is how I would do it.
Stack1: 2 3 4 5 6 which is essentially an array
2 is the bottom of the stack and 6 is the top of the stack.
Stack2: empty
Insert an element to Queue:
This is very simple. Just add to the end of array i.e stack1
stack1:2 3 4 5 6 7
Now 7 is the top of the stack.
Delete an element from Queue:
1. Pop all elements in stack1 and insert them to stack2. So, your array will be reversed
stack1:empty
stack2: 7 6 5 4 3 2 . Now 2 is at the top of the stack.
2. Now your top(stack2) will be pointing to 2. Just pop it.
7 6 5 4 3
3. Now for the remaining elements in stack2, pop from stack2 and insert them to stack1.
stack2:empty
stack1:3 4 5 6 7
PS: The above algorithm assumes that you know how to manage memory for arrays as it shrinks or expands.
I think you actually can implement a queue using two adjacent stacks as you described. The problem is that you cannot implement those two adjacent stacks with an array efficiently. I mean your queue seems OK, but when you try to use the underlying stacks, you encounter the problem how to insert a new item at the beginning of the array (i.e. push to stack1). You need to move (copy) all items in your array to push an item into stack1. And that's ill design.
For those who are looking for the solution, a sample one is this:
Let's say we have two stacks S1 and S2.
A queue has the given two behaviours:
Enqueue: Insert an element into the queue. For this, simply push into S1.
Dequeue: Pop all elements from from S1 one by one, simultaneously pushing them into S2. Now pop from S2. The popped element is the desired result of Dequeue.
Readers are encouraged to find more optimized solutions to this and post them here if possible :)
Here is an example in python using the built in array/list for two stacks.
class Queue2Stacks(object):
def __init__(self):
self.in_stack = []
self.out_stack = []
def enqueue(self, element):
self.in_stack.append(element)
def dequeue(self):
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
return self.out_stack.pop()
Related
I have a m x m two-dimensional array and I want to randomly select a sequence of n elements. The elements have to be adjacent (not diagonally). What is a good approach here? I though about a depth-first search from a random starting point but that seemed a little bit overkill for such a simple problem.
If I get this right, you are looking for sequence like continuous numbers ?
When i simplyfy this:
9 4 3
0 7 2
5 6 1
So when the 1 is selected, you'd like to have path from 1 to 4 right ? I personally think that Depth-First search would be the best choice. It's not that hard, it's actually pretty simple. Imagine you select number 2. You'll remember position of number 2 and then you can look for lowest numbers until there are any. When you are done with this part, you just do the same for higher numbers.
You have two stacks one for possible ways and another one for final path.
When going through the array, you are just poping from possibilities and pushing right ones into the final stack.
The best approach would be finding the lowest possible number without saving anything and then just looking for higher numbers and storing them so at the end you'll get stack from the highest number to the lowest.
If I get that wrong and you mean just like selecting elements that are "touching" like (from my table) 9 0 7 6, which means that the content doesn't matter, then you can do it simple by picking one number, storing all possibilities (every element around it) and then pick random number from 0 to size of that stored values. When you select one, you remove it from these stored values but you keep them. Then you run this on the new element and you just add these new elements to stored elements so the random will always pick surrounding around these selected numbers.
I'm new to C programming and I kinda need some help in the frontBackSplitLinkedList part,
For example, assume that given linked list is: 2 6 7 8 9
The resulting front and back are:
front: 2 6 7
back: 8 9
I've searched through some websites but most of the codings are using nodes instead of linked list.
Any idea how to do this? Thank you!
You do not actually have to count elements in list, as far as i see it, you store the number of elements in _linkedlist. You can always use that value to split however you like. I would strongly suggest to first simlify your List, so it can add elements only to the back or the front of the List, it will be easier to work with it, but won't really affect the principle of split function.
If I understand your question correcly then you want to split the list in the middle, where un uneven list will be split a frontlist that is one larger than the backlist.
First of all you must have a count of the list length. I propose that you walk the list, counting the number of list nodes.
Then you divide that number as follows:
count = (count+1)/2;
Now we need to know if you must create two new lists (so you have to make copies of all the list nodes), or whether the old list may be reused. Assume it may be reused, then you assign the old list to frontlist, walk count listnodes, asign that one to backlist and set the next member of the one before it to NULL.
You are done now, except that the caller may no longer use the original list (it has become equivalent, and actually is, frontlist).
Recently I came across a question, I had to code it but failed to do so effectively. So i'll try to explain the question in the best way I can, and it goes like..
There are different people belonging to different communities. Say for example, 1 belongs to C1, 2 belong to C2 and 3 belongs to C3. We can perform two operations, Query and Join. Query returns the total number of people belonging to the person's community. And Join is used to combine the communities of exactly two persons into one.
We are taking the number of people and the number of operations to be performed as an input and we need to produce the result onto the standard output.
Example Case: (Q -> Query and J -> Join)
3 // No. of People
6 // No. of Operations
Q 1 // Prints 1
J 1,2 // Joins communities of 1 and 2
Q 1 // Prints 2
J 2,3 // Joins communities of 1 and 2
Q 3 // Prints 3
Q 1 // Prints 3
So essentially, its like people are belonging to individual bubbles initially and on join, we join the bubbles of two peoples to form a larger bubble containing two people.
There are different ways to solve this problem. Using ArrayList methods of Java, its pretty easy. I was trying to solve it using arrays.
My approach was to form an array for each person initially and as we join two communities, the respective arrays are added with the people as described :
Arr1 : 1 // Array for Person 1 ; Size 1
Arr2 : 2 // Array for Person 2 ; Size 1
J 1,2 results in,
Arr1 : 1,2 // Size 2
Arr2 : 2,1 // Size 2
But I was told that this is not an effective approach, an effective approach would be to make use of Linked List. I was unable to use linked list to solve it. So I would like some inputs from you guys on the approach, how exactly do I make use of Linked List to keep track of Join operations?
Sorry for the long post, and thanks in advance :)
P.S : I am not sure if the title is appropriate, kindly suggest proper title in case its not appropriate.
I do not know why somebody felt that linked lists would be better than arrays in this instance, but joining the communities is as simple as adding all of the members of one to the other, and changing all the pointers that point to the now empty community to point to the node containing all of the members. Query should be simple enough that it goes without saying.
I was trying to think of an algorithm which chooses 6 random cells from an array with 50 cells, such that the probability for each cell to be picked is equal.
I need to find a solution that uses the function Random(start,end) no more than 6 times.
I can't use any extra data structure, and it is important that the probability for each cell to be picked will be equal and independent.
Call Random(0,49). Read the resulting cell, then shuffle everything after it in the array down one place so that you have a 49-cell array with the picked value missing.
Call Random(0,48) and repeat 6 times.
Put the cells in a list, shuffle it, take six of 'em
I want to declare a two-dimensional array with two different data types in C language. First column and row must be character and they are the same and other elements must be integer. Then, I want to set the values of the elements based on the first column and row. For example:
A B C D
A 1 2 3 4
B 4 3 2 1 a[A][D] = 4
C 9 8 7 6
D 6 7 8 9
I cannot use a[0][3] = 4, because A and D are returned values of another function in my program and I don't know what there indeces are in the array a. If I use another array for my first row and search in it to find the index, it takes too much time and it is not good for the performance of my program.
In C, you cannot declare an array, two-dimensional or otherwise, such that some parts of the array are of one type and some are of another type. It is possible to cheat, and use the larger of the two data types for the entire array and then cast a whole bunch, but I do not recommend that idea for your problem, since it's more error-prone and gives up what little illusion of type safety C has.
If I use another array for my first row and search in it to find the index, it takes too much time and it is not good for the performance of my program.
Build a correct solution first, and then optimize if the correct solution isn't fast enough. If you have such a solution, please post it. If not, write it and then, if it isn't fast enough, ask another question on how to optimize it.