Linklist Interview Question

How to print the node of the given linked list

If you're new to linked lists, this is a great exercise for learning about them. Given a pointer to the head node of a linked list, print its elements in order, one element per line. If the head pointer is null (indicating the list is empty), don’t print anything.
Input Format
The void Print(Node* head) method takes the head node of a linked list as a parameter. Each struct Node has a data field (which stores integer data) and a next field (which points to the next element in the list).
Note: Do not read any input from stdin/console. Each test case calls the Print method individually and passes it the head of a list.
Output Format
Print the integer data for each element of the linked list to stdout/console (e.g.: using printf, cout, etc.). There should be one element per line.
Sample Input
This example uses the following two linked lists:
NULL
1->2->3->NULL
and are the two head nodes passed as arguments to Print(Node* head).
Note: In linked list diagrams, -> describes a pointer to the next node in the list.
Sample Output
1 2 3 ExplanationTest Case 0: NULL. An empty list is passed to the method, so nothing is printed.
Test Case 1: 1->2->3->NULL. This is a non-empty list so we loop through each element and printing each element's data field on its own line.
Here i am only providing the main function you have to create the link list first then only you can print its nodes.
/* Print elements of a linked list on console head pointer input could be NULL as well for empty list Node is defined as struct Node { int data; struct Node *next; } */ void Print(Node *head) { // This is a "method-only" submission. // You only need to complete this method. while(head!=NULL) { cout<<head->data<<endl; head = head->next; } }Note that this approach is not only specific to this type of question you can use this sorting technique in various questions such as if you want to check whether to word are anagrams of one another or not. You can simply sort them and compare them to find out. This approach is also helpful in other questions so i suggest that its better to learn this tricks and keep in mind while attempting the question you may find it useful. You can always search for more coding problems like this to get comfortable to this to approach or you can find new problems where this approach is applicable. So go and search more problems like this and check whether this approach is useful or not and you can tell me about it by commenting and writing about this to me.
Try more and more problems that you find on string and arrays and try to develop an approach the will help you understand problems rather then learning the solution. Once you know how to approach the problem you will able to solve any problem related to strings and array. I wish best of luck to you for your future.
0 comments:
Post a Comment