Pergunta de entrevista da empresa NVIDIA
There is a singly linked list of ints, write a function that takes the head pointer, and prints the list in reverse order
Respostas da entrevista
void func(node *p) {
if (node->next)
func(node->next);
printf(whatever is stored in the node);
}
This is nice solution, however you need to take care that if the list is very big then you might encounter stack over flow.
For better solution better considering implementation without recursion.
For example:
You can use a simple stack and push the node property to it every iteration (starting from the head)
When finishing the iteration over the list, pop the node property from the stack and print it.
the stack is fine as long as it doesnt over flow also !
If this is possible, then may be reverse the list, print it, then reverse it back O(n)
#include
#include
#include
#include
using namespace std;
template
struct NodeList
{
public:
template
class Node
{
public:
U data;
std::shared_ptr next;
Node(T data):data(data) { std::cout > head = nullptr;
public:
void push(T);
void print();
int size();
void printReverse();
};
template
void NodeList::push(T val)
{
if(head == nullptr)
{
head = std::make_shared>(val);
return;
}
std::shared_ptr> end = head;
while(true)
{
if(end->next == nullptr)
{
break;
}
end = end->next;
}
end->next = std::make_shared>(val);
}
template
void NodeList::print()
{
if(head == nullptr)
{
return;
}
std::shared_ptr> temp = head;
while(temp->next != nullptr)
{
std::cout data next;
}
std::cout data
void NodeList::printReverse()
{
if(head == nullptr)
{
return;
}
vector mydata;
std::shared_ptr> temp = head;
while(temp->next != nullptr)
{
mydata.push_back(temp->data);
temp = temp->next;
}
mydata.push_back(temp->data);
std::for_each(mydata.rbegin(), mydata.rend(), [](int a) { std::cout
int NodeList::size()
{
if(head == nullptr)
{
return 0;
}
int num = 1;
std::shared_ptr> temp = head;
while(temp->next != nullptr)
{
temp = temp->next;
num += 1;
}
return num;
}
int main()
{
NodeList list;
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(5);
list.print();
int sizet = list.size();
std::cout << "size is " << sizet << std::endl;
list.printReverse();
return 0;
}