Categories
Uncategorized

Algorithm to reverse a linked list in O(n) time

Implement an algorithm to reverse a linked list. Now do it without recursion.

One reply on “Algorithm to reverse a linked list in O(n) time”

Ok, so this function reverses a linked list in O(N) time. Walk through the list removing elements and then adding the forming a new list with them inserted in reverse order. Then update the origional list pointer.

Use: listHead = revList( listHead );

Code.

node *revList( node *curList )
{
  node *oldHead = curList;
  node *newHead = (node *) NULL;
  node *tmpNode;

  if(curList == (node *)NULL)
    return((node *)NULL);

  while( oldHead != (node *)NULL){
    tmpNode = oldHead;
    oldHead = oldHead->next;

    tmpNode->next = newHead;
    newHead = tmpNode;
  }

  return(newHead);
}

Leave a Reply