Tuesday, March 8, 2011

Reverse a singly linked list

1. Reverse a singly linked list


//
// iterative version
//
Node* ReverseList( Node ** List )
{

Node *temp1 = *List;
Node * temp2 = NULL;
Node * temp3 = NULL;

while ( temp1 )
{
*List = temp1; //set the head to last node
temp2= temp1->pNext; // save the next ptr in temp2
temp1->pNext = temp3; // change next to privous
temp3 = temp1;
temp1 = temp2;
}

return *List;
}

No comments:

Post a Comment