Monday, June 15, 2015

Google Question: Reverse linked list without using recursion.

Problem: Reverse the linked list without using recursion.

Solution: It is straight forward, can be easily understood by implementation.

Implementation:

        public void Reverse()
        {
            LinkedListNode prev = null, curr = this.Head;
            while (curr != null)
            {
                var next = curr.Next;
                curr.Next = prev;
                prev = curr;
                curr = next;
            }

            this.Head = prev;
        }

Complexity: O(n)

No comments:

Post a Comment