LinuxQuestions.org
View the Most Wanted LQ Wiki articles.
Go Back   LinuxQuestions.org > Blogs > TheIndependentAquarius
User Name
Password

Notices



Rating: 2 votes, 5.00 average.

How to reverse a linked list? - C

Posted 02-01-2012 at 06:49 AM by TheIndependentAquarius



Code:
void reverseLinkedList ()
{
	linkedList *pointer1;
	linkedList *pointer2;
	
	pointer1 = NULL;
	pointer2 = head->next;
	
	while (pointer2 != NULL)
	{
		head->next = pointer1;
		
		pointer1     = head;
		head         = pointer2;
		pointer2     = pointer2->next;
	}
	
	/*
             When
		`pointer1` reaches the last but one node,
		`head` reaches the last node,
		`pointer2` reaches the null,
		
		the direction change of the head node's next pointer is still pending, so
	*/
	head->next = pointer1;

	/* 
             To include the direction change of the head node's next pointer (when it 
	        reaches the end of the list) in the while loop itself, simply store the head 
        	pointer in another temporary pointer i.e pointerX. The condition in the while 
	        loop then will be `while (pointerX != NULL)` and you'll have to check the value
        	of the `pointer2` before moving it again, like 
	        `if (pointer2 != NULL) pointer2 = pointer2->next;`
        */
}
Attached Files
File Type: txt reverseLinkedList.txt (1.8 KB, 5 views)
Posted in Data structures
Views 1151 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 05:32 AM.

Main Menu
Advertisement

Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration