Answer:
Printing a singly linked-list in reverse in O(N) time
Step 1. Create an empty stack.
Step 2. Traverse each element of linked-list and push it in stack. O(N)
Step 3. Pop stack and print the element untill stack gets empty. O(N)
O(N) + O(N) = O(N)
This algorithm will take O(N) extra space for maintaining the stack.
class Node {
int data;
Node next;
}
Stack<Integer> st = new Stack<Integer>();
current = head; // head is starting point of linked-list
while(current != NULL)
{
st.push(current.data);
current = current.next;
}
while( ! st.empty())
{
System.out.println( st.pop() + " ");
}
Step-by-step explanation: