Data Structure Linked list Question:
How to reverse singly link list?
Answer:
Reverse a singly link list using iteration:-
1. First, set a pointer ( *current) to point to the first node i.e. current=base
2. Move ahead until current!=null (till the end)
3. set another pointer (* next) to point to the next node i.e. next=current->next
4. store reference of *next in a temporary variable ( *result) i.e current->next=result
5. swap the result value with current i.e. result=current
6. and now swap the current value with next. i.e. current=next
7. return result and repeat from step 2
A linked list can also be reversed using recursion which eliminates the use of a temporary variable.
1. First, set a pointer ( *current) to point to the first node i.e. current=base
2. Move ahead until current!=null (till the end)
3. set another pointer (* next) to point to the next node i.e. next=current->next
4. store reference of *next in a temporary variable ( *result) i.e current->next=result
5. swap the result value with current i.e. result=current
6. and now swap the current value with next. i.e. current=next
7. return result and repeat from step 2
A linked list can also be reversed using recursion which eliminates the use of a temporary variable.
Previous Question | Next Question |
Explain the steps to insert data into a singly linked list? | What is circular linked list? |