Wednesday, October 12, 2011

Reverse a Singly Linked List

Problem: reverse a singly linked list.

Thinking: there may be several 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 1.

Requirement for Case 1: O(n) in time and O(1) in space.
Idea: use 2 pointers for exchange and a 3rd one to temporarily record the next node.
Code:


Related Posts:
Discussion about Case 2
Discussion about Case 3

No comments:

Post a Comment