How to reverse the Stack? - algorithm

May be it is too easy question but Please share how to reverse any kind of stack?

The right answer may be "don't reverse a stack."
If some constraint means you absolutely have to reverse a stack, your question is already answered. But, I can't help but wonder why you want to reverse a stack -- to me, that means you are using the wrong data structure.
If its all pushes, then the reverse, then all pops; thats a queue.
If pushes, pops, and reverses are mixed in random order, you probably want a data structure that specifically supports those operations... it will be confusing when someone reads "stack" but the structure is really something else.
Not sure about scala, but some languages have a double-ended queue to specifically represent a linear collection with access to the head and tail elements -- that may be exactly what you need. If not, a doubly-linked list will do nicely; or a plain old list will do if an O(n) pop()-equivalent isn't an issue.
If your pop() equivalent operation isn't aware of which end to get an element from (e.g., one piece of code is calling reverse, and some other code just says "give me an element" and isn't aware of whether or not reverse has been called), encapsulate the queue with a flag for direction as follows. This will give you the same functionality without having to actually reverse anything.
(sorry for the very-pseudo code, scala isn't in my toolbox).
ReversableStack {
DoublyLinkedList backingStore;
Boolean forward;
get() {
if (forward) return backingStore.take_head();
else return backingStore.take_tail();
}
put(item) {
if (forward) backingStore.add_head(item);
else backingStore.add_tail(item);
}
reverse() {
forward = !forward;
}
}

make new stack;
while (old stack not empty)
x = pop(old stack)
push x on new stack
Or call reverse on the stack, but note that that returns a List if applied to a mutable.Stack. It does return a Stack if you use immutable.Stack.

I don't speak Scala, but according to the doc you simply call reverse on the stack.

public void reverse(Stack st) {
int m = (int)st.Pop();
if (st.Count != 1)
reverse(st);
Push(st , m);
}
public void Push(Stack st , int a) {
int m = (int)st.Pop();
if (st.Count != 0)
Push(st , a);
else
st.Push(a);
st.Push(m);
}

Just loop around popping values from it and pushing them into another stack.

Related

Direct accessing a nested Map of dynamic depth

I want to input data in a map at its depth. It is easy to do the following:
static Map map;
insert(keyList, x) {
if(keyList.length==1) map[0] = x;
if(keyList.length==2) map[keyList[0]][keyList[1]] = x;
...
}
I would, however, like a more intuitive way to do the same (i.e. using a loop over the keyList) which does not rely on hardcoding iterations.
My attempt at implementing the same led to a resource-heavy recursive implementation:
Map insertInMap(Map<String, dynamic> m, List<String> keyList, Object o) {
if (keyList.length == 1) {
m[keyList.first] = o;
} else {
m[keyList.first] = insertInMap(
Map.from(m[keyList.first]),
keyList.sublist(1),
o,
);
}
return m;
}
I understand the above code is making copies of the Map and refitting them in the original map bottom up. I would like a way to edit the map directly, similar to how map[i][j] works, which I believe does not replicate maps and should thus be much more efficient in memory use as an in-place algorithm.
My search led me to this as question;
Accessing nested array at a dynamic depth which resembles my non-optimal recursive solution. Other answers I attempted searching were about iterating over maps using loops, which are a different topic altogether without the mention of their depth.
If it is not possible, assistance by way of confirming it would save me time and mental anguish.
Thanks in advance.

How do I make this code for detecting palindrome in a Linked List cover all cases?

So, I was solving this problem of detecting a palindrome in a linked list. I came up with the following solution for it:
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode temp=head;
boolean [] arr = new boolean[10];
int count=0;
if(head==null) return false;
while(temp!=null)
{
if(arr[temp.val]==false)
arr[temp.val]=true;
else
arr[temp.val]=false;
temp=temp.next;
}
for(int i=0;i<10;i++)
{
if(arr[i]==true)
count++;
}
if(count<2)return true;
return false;
}
Now, the logic behind this solution is correct as far as I can see but it fails for cases like this: [1,0,0], [4,0,0,0,0] etc. How do I overcome this? (Pls dont reply with a shorter method I want to know the reason behind why this fails for certain cases.)
First of all Welcome to StackOverflow!
Because of how simple this problem's solution can be I feel obligated to tell you that a solution with an auxiliary stack is not only easy to implement but also easy to understand. But since you asked why your code fails for certain cases I'll answer that question first. Your code in particular is counting the number of digits that have an odd count.
Although this seems to be what you are supposed to do to detect a palindrome notice that a linked list that looks like 1 -> 1 -> 0 -> 0 is also considered a palindrome under your code because the count is always going to be less than 0.
Your solution works for telling us if it is possible to create a palindrome given a set of digits. Suppose that the question was like "given a linked list tell me if you can rearrange it to create a palindrome" but it does not work for "is this linked list a palindrome".

recursion in sorted double linked list insertion

I'm new to the data structures and recursion concept. I'm struggling to understand why and who he was able to use the recursion in this concept. I found this code in the forums for this and I couldn't really understand the concept of this. For simple case of 2 1 3 4, if any one can explain the iteration steps, it will be greatly appreciated on my behalf.
Here is the link for hacker rank:
https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list
Node SortedInsert(Node head,int data) {
Node n = new Node();
n.data = data;
if (head == null) {
return n;
}
else if (data <= head.data) {
n.next = head;
head.prev = n;
return n;
}
else {
Node rest = SortedInsert(head.next, data);
head.next = rest;
rest.prev = head;
return head;
}
}
Recursion:
Recursion means a function calls itself. It is used as a simple way to save state information for algorithms that require saving of multiple states, usually a large number of states, and retrieving them in reverse order. (There are alternative techniques that are more professional and less prone to memory issues, such as using a Stack object to save program state).
This example is poor but typical of intro to recursion. Yes, you can iterate through a linked list using recursion but there is absolutely no reason to. A loop would be more appropriate. This is purely for demonstrating how recursion works. So, to answer your question "Why?" it is simply so you can learn the concept and use it later in other algorithms that it actually makes sense.
Recursion is useful when instead of a linked list you have a tree, where each node points to multiple other nodes. In that case, you need to save your state (which node you are on, and which subnode you called last) so that you can traversing one of the linked nodes, then return and go to the next node.
You also asked "how". When a function calls itself, all of its variables are saved (on the program stack) and new ones are created for the next iteration of itself. Then, when that call returns, it goes back to where it was called from and the previous set of variables are loaded. This is very different from a "jump" or a loop of some kind, where the same copies of the variables are used each time. By using recursion, there is a new copy of every local variable each time it is called. This is true even of the "data" variable in the example, which never changes (hence, one inefficiency).

Recursion transformation without stack frames code repetitions

I have the following pseudo-code:
function X(data, limit, level = 0)
{
result = [];
foreach (Y(data, level) as entity) {
if (level < limit) {
result = result + X(entity, limit, level + 1);
} else {
//trivial recursion case:
result = result + Z(entity);
}
}
return result;
}
which I need to turn into a plain (e.g. without recursive calls). So far I'm out of ideas regarding how to do that elegantly. Following this answer I see that I must construct the entire stack frames which are basically the code repetitions (i.e. I will place same code again and again with different return addresses).
Or I tried stuff like these suggestions - where there is a phrase
Find a recursive call that’s not a tail call.
Identify what work is being done between that call and its return statement.
But I do not understand how can the "work" be identified in the case when it is happening from within internal loop.
So, my problem is that all examples above are providing cases when the "work can be easily identified" because there are no control instructions from within the function. I understand the concept behind recursion on a compilation level, but what I want to avoid is code repetition. So,
My question: how to approach transformation of the pseudo-code above which does not mean code repetitions for simulating stack frames?
It looks like an algorithm to descend a nested data structure (lists of lists) and flatten it out into a single list. It would have been good to have a simple description like that in the question.
To do that, you need to keep track of multiple indices / iterators / cursors, one at each level that you've descended through. A recursive implementation does that by using the call stack. A non-recursive implementation will need a manually-implemented stack data structure where you can push/pop stuff.
Since you don't have to save context (registers) and a return address on the call stack, just the actual iterator (e.g. array index), this can be a lot more space efficient.
When you're looping over the result of Y and need to call X or Z, push the current state onto the stack. Branch back to the beginning of the foreach, and call Y on the new entity. When you get to the end of a loop, pop the old state if there is any, and pick up in the middle of that loop.

Changing from recursion to iteration

I have my function that needs changing to iteration, because of very slow executing of it.
There are two recursive calls, depends which condition is true.
It's something like this:
(I have static array of classes outside function, let's say data)
void func(int a, int b, int c, int d) {
//something
//non-recursive
//here..
for (i=0; i<data.length; i++) {
if (!data[i].x) {
data[i].x = 1;
if (a == data[i].value1)
func(data[i].value2,b,c,d);
else if (a == data[i].value2)
func(data[i].value1,b,c,d);
data[i].x = 0;
}
}
}
!!
EDIT: Here is my algorithm: http://pastebin.com/F7UfzfHv
Function searches for every paths from one point to another in graph, but returns (to an array) only one path in which are only unique vertices.
!!
And I know that good way to manage that is to use stack... But I don't know how. Could someone give me a hint about it?
There is a good possibility that your function might be computing the same thing again and again, which in technical terms is called as overlapping sub-problems(if you are familiar with the dynamic programming then you might know). First try to identify whether that is the case or not. Since you haven't told anything about what function do and I can't tell the exact problem.
Also the thing you are talking about using a stack is not of great use since recursion uses a stack internally. Using external stack instead of internal is more error prone is not of great use.

Resources