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

Sigiloso

16 de fev. de 2012

void func(node *p) { if (node->next) func(node->next); printf(whatever is stored in the node); }

5

Sigiloso

8 de jun. de 2012

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.

2

Sigiloso

13 de jul. de 2012

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)

1

Sigiloso

1 de dez. de 2018

X is 1

Sigiloso

22 de nov. de 2021

#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; }