Reverse a linked list

Me@earth's Avatar
Go4Expert Member
Can anyone help me with a code to reverse a linked list
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
This should help http://www.go4expert.com/showthread.php?t=4593
0
aali's Avatar, Join Date: Jul 2008
Go4Expert Member
Code:
void SinglyLinkedList::reverse()
	{
		/********************
		Node* currentFirst;
		Node* currentLast;
		 currentFirst=first_ptr;
		***********************
		if(first_ptr==NULL||first_ptr->next==NULL)
			return;
		
		Node*current=first_ptr->next;
		Node *pervious=first_ptr;
		Node*after;
		first_ptr->next=NULL;
		while(current!=NULL)
			{
			after=current->next;
			current->next=pervious;
			pervious=current;
			current=after;

			}
		first_ptr=pervious;
		*********************/
	/**********other way**********/
	if(first_ptr==NULL||first_ptr->next==NULL)
			return;
		
		Node*current=first_ptr->next;
		//Node *pervious=first_ptr;
		Node*newNode=NULL;
		first_ptr->next=NULL;
		while(current!=NULL)
			{
			newNode=current->next;
			current->next=first_ptr;
			first_ptr=current;
			current=newNode;

			}
		//first_ptr=pervious;
    
	/*********************************/
	
	}

Last edited by shabbir; 22Jul2008 at 21:59.. Reason: Code block