Thursday, October 13, 2011

Reverse a Singly Linked List

Problem: reverse a singly linked list.

Three cases:
  1. Acyclic list
  2. Completely cyclic list (all nodes are in the cycle/loop)
  3. Partially cyclic list (at least one node not in the cycle/loop)
This post discusses Case 2.
Requirement: O(n) in time and O(1) in space.

Case 2 is similar to Case 1, except for the test condition of list tail and the corresponding update to original head.

Here is the code for this case.


Related Posts:
Discussion about Case 1
Discussion about Case 3

No comments:

Post a Comment