Part 15 of 22 in Linked List - set 01  

Print elements in a singly linked list by animeshn

Problem statement

Given a pointer to the head of a linked list, write a method to print all the elements in the linked list. The head of the linked list could also be NULL i.e the linked list could also be empty.

Input

Your method will have one arguments - pointer to the head of linked list.

Output

Your method should print each element of the linked list on a single line on console.

1) Are you writing the main function and definition of Node also? 
    You will get compilation error.
    You only need to write the Print function. 

One of the basic operations performed when playing with linked lists. The idea here is to have a temporary pointer that iterates from head of the linked list to its tail.

Lets call our temporary pointer as iterating pointer (as per its role).

Initializing our iterating pointer to head makes it point to the beginning of the list. At each step, we print the data corresponding to the current node, and move to the next node in the list.

We go on doing this till we reach the end of the list.

We recognize the end of our list when our iterating pointer does not point to any node, i.e. it is NULL, and so we terminate.

Steps

  1. Declare and initialize iterating pointer.
  2. Check if the iterating pointer points to the end of list, if yes then terminate the loop.
  3. Print data corresponding to the current node.
  4. Iterate the iterating pointer (iter = iter->next).
  5. Go to Step 2.

editorial written by shivshnkr

void Print(Node *head)
{
	/* function to print all the elements of linked list */

	/* declare and initialize an iterating pointer for looping 
	   through the list */ 
	Node *iter = head;

	while (iter != NULL) /* loop till end of list */
	{
		/* print data corresponding to current node */
		cout << iter->data << endl;

		/* iterate to the address of next node */
		iter = iter->next;
	}
	return;
}

featured solution by shivshnkr



To try out your code



Sign in

Sign up