Interview Question

Interview Seattle, WA

How to print a link list reversely

data structures

Interview Answer

3 Answers


The simplest solution would be: 1. Traverse a linked list from head to tail 2. During traversal, push all the elements of the node into a stack 3. Once the traversal is done, pop all elements and this will print the linked list in reverse order ... Looking fwd for an optimized solution ...

Vikas on Jun 16, 2012

void printLLreverse(Node *headNode) { //this is going to just iterate through the LL //add each element to a stack and //print the stack when we are finished stack <int> llStack; Node* currNode = headNode; while(currNode) { llStack.push(currNode->data); currNode = currNode->next; } while(llStack.size() > 0) { cout <<; llStack.pop(); } }

anonymous on Sep 25, 2012

the stack solution is good, you can also use recursion void printReverse(ListNode node) { if(node == null) return; printReverse(; System.out.println(node.value); }

helloslz on Dec 29, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.