The Problem Complete the function printList that accepts a node * (the head of a
ID: 3793530 • Letter: T
Question
The Problem
Complete the function printList that accepts a node * (the head of a linked list) as a parameter and print out the list in the following format:
If the list is empty then the function should print "Empty list".
You should complete the main function to test your printList in, at least, the following cases:
An empty list
A list with exactly one node
A list with more than one node (eg: 100 -> 200 -> 300, as shown above)
//main.cpp
#include <iostream>
using namespace std;
struct node {
int val;
node *next;
};
void printList(node *head) {
// printList function
}
int main() {
// Test 1: An empty list
node * head = NULL;
printList(head);
// Test 2: A list with exactly one node
// Test 3: A list with more than one node
return 0;
}
Explanation / Answer
#include <iostream>
using namespace std;
struct node {
int val;
node *next;
};
void printList(node *head)
{
int i = 0;
if(head == NULL) // if head is NUll it is empty list
{
cout<<" Empty list";
}
while(head != NULL) //while end of the list is not reached
{
cout<<" Node "<<i<<":"<<head->val;
head = head->next; // traverse next node
}
}
int main() {
// Test 1: An empty list
cout<<" list with no node";
node *head = NULL;
printList(head);
// Test 2: A list with exactly one node
cout<<" list with one node";
node *node1 = new node; //make new node
node1->val= 100; //assign its value to 100
node1->next = NULL; //assign its next pointer to null
head= node1; // make it the head node as head is null
printList(head); // call printList function
// Test 3: A list with more than one node
cout<<" list with three nodes";
node *node2 = new node;
node2->val= 200;
node2->next = NULL;
node1->next = node2;
node *node3 = new node;
node3->val= 300;
node3->next = NULL;
node2->next = node3;
printList(head);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.