Download your favorite Linux distribution at LQ ISO.
Go Back > Blogs > TheIndependentAquarius
User Name


Rating: 2 votes, 5.00 average.

How to reverse a linked list? - C

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

void reverseLinkedList ()
	linkedList *pointer1;
	linkedList *pointer2;
	pointer1 = NULL;
	pointer2 = head->next;
	while (pointer2 != NULL)
		head->next = pointer1;
		pointer1     = head;
		head         = pointer2;
		pointer2     = pointer2->next;
		`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 1585 Comments 0
« Prev     Main     Next »
Total Comments 0




All times are GMT -5. The time now is 04:10 AM.

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