190k views
4 votes
Write an iterative algorithm in Java-like pseudocode for printing a singly linked list in reverse in O(N) time. You can use as much extra space as you need. The original list pointers CAN NOT BE MODIFIED. State in big-O notation how much extra space is used by this algorithm.NOTE: The reason you are not allowed to implement the algorithms recursively, is due to the additional space requirements of recursive calls. Around N recursive calls has an additional space complexity of O(N) as each recursive call is placed on a call-stack that requires memory to keep track of.Write another iterative algorithm in Java-like pseudocode for printing a singly linked list in reverse using O(1) extra space. The original list pointers CAN NOT BE MODIFIED. This algorithm can have any runtime (it will be worse than the algorithm in part a). State the runtime of your algorithm in big-O notation.NOTE: The reason you are not allowed to implement the algorithms recursively, is due to the additional space requirements of recursive calls. Around N recursive calls has an additional space complexity of O(N) as each recursive call is placed on a call-stack that requires memory to keep track of.

User JHeni
by
6.4k points

1 Answer

2 votes

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:

User Ivan Burlutskiy
by
6.5k points