I was working on a code related to reversing parts of linked lists. For the reversal part, the algorithm I was using was to push the nodes of the list onto a stack, and then keep popping the stack and correct the next pointer of each node. The question that I had was that would using the STL stack provide a better performance over the function call stack, or vice-versa.
I had expected the STL stack to perform better because there are other overheads with calling a function stack, but from the submission details it seems otherwise. Did I miss something, or does the function stack somehow perform better?
Thanks for any help provided.
Attaching the code also, in case someone wants a look. The parameters to the reverse between function are the head of the list, and the two indexes (1 based, inclusive), between which the nodes should be reversed. I don't think you need to go through the code though:
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n)
{
int counter = 1;
stack<ListNode*> holder;
ListNode* current = head;
ListNode* pre_flip = NULL;
ListNode* to_return = head;
while (counter < m)
{
pre_flip = current;
current = current->next;
counter++;
}
while (counter <= n)
{
holder.push(current);
if (counter != n)
current = current->next;
counter++;
}
if (m == 1)
to_return = current;
ListNode* post_flip;
post_flip = current->next;
if (pre_flip == NULL)
pre_flip = to_return;
while (holder.empty() == 0)
{
ListNode* temp = holder.top();
pre_flip->next = temp;
pre_flip = pre_flip->next;
holder.pop();
}
pre_flip->next = post_flip;
return to_return;
}
};