In: Computer Science
1.Please write a C++ program that counts the nodes in a linked list with the first node pointed to by first. Also please explain. 2. Write a program to determine the average of a linked list of real numbers with the first node pointed to by first. 3. Determine the computing times of the algorithms in question 1 and 4. Write a program to insert a new node into a linked list with the first node pointed to by first after the nth node in this list for a given integer n. 5. Write a program to delete the nth node in a linked list with the first node pointed to by first, where n is a given integer.
Answer 1
In the structure, we have two members:
Next we need a list to be able to count it. This function adds a node at the end of the list.
To do this:
Now we define a helper function, printList() to see the current linked list.
Here, we use a single pointer for head. This means any change to head does not reflect in main().
Now this is the required function for question 1, countNode().
To do this, we initialize a count variable to zero. Then we iterate the list, and in each iteration we increment count by one. As soon as the list ends, we get the number of nodes in count. Then we return count to main().
Here is the entire program:
#include <iostream>
using namespace std;
/*
Defining the structure for Node
*/
struct Node
{
double num; // To store the real number
Node *next; // To store pointer to next node
};
/*
Function to add a node to the list
Arguments:
**head -> Double pointer to the first node of the list
*/
int addNode(Node **head)
{
Node *new_node = NULL; // The new node
double input_num; // Get the real number from user
// Defining the new node
new_node = new Node;
cout << "Enter a number: ";
cin >> input_num;
new_node->num = input_num;
new_node->next = NULL;
// Case when first node is added to list, i.e. the when list is empty
if(*head == NULL)
{
*head = new_node;
}
// Otherwise
else
{
Node *temp = *head;
// Iterate to the last node in list
while(temp->next != NULL)
temp = temp->next;
// Add the new node to the list
temp->next = new_node;
}
return 0;
}
/*
Function to count the number of nodes in the list
Arguments:
*head -> pointer to the first node in the list
Return value:
The count of nodes in the list.
*/
int countNode(Node *head)
{
int count = 0;
// Iterating the entire list
while(head != NULL)
{
// Increasing the count of nodes by one in each iteration
++count;
head = head->next;
}
return count;
}
/*
Function to print the list
Arguments:
*head -> Pointer to the first node in the list
*/
int printList(Node *head)
{
cout << "The list is:" << endl;
while(head != NULL)
{
cout << head->num << " -> ";
head = head->next;
}
cout << "NULL" << endl;
return 0;
}
int main()
{
Node *first = NULL;
int choice, count;
double avg;
// Displaying the options available to the user
cout << "MENU" << endl;
cout << "1. Add node" << endl;
cout << "2. Count nodes" << endl;
cout << "3. Print the list" << endl;
cout << "4. Exit" << endl;
do
{
// Take choice from user
cout << "Enter your choice: ";
cin >> choice;
// Do task according to the choice
switch(choice)
{
case 1:
addNode(&first);
break;
case 2:
count = countNode(first);
cout << "Number of nodes in the list: " << count << endl;
break;
case 3:
printList(first);
break;
case 4:
cout << "Bye!!" << endl;
break;
default:
cout << "Sorry!! No such choice. Please try again." << endl;
}
}while(choice != 4);
return 0;
}
Sample output:
Answer 2
To calculate the average of real numbers in the list, we iterate through the list. In each iteration, we add the real number (in the node) to the variable sum. Also, we increment the count variable by one. At the end, we return sum/count.
Here is now the final code for question 2:
#include <iostream>
using namespace std;
/*
Defining the structure for Node
*/
struct Node
{
double num; // To store the real number
Node *next; // To store pointer to next node
};
/*
Function to add a node to the list
Arguments:
**head -> Double pointer to the first node of the list
*/
int addNode(Node **head)
{
Node *new_node = NULL; // The new node
double input_num; // Get the real number from user
// Defining the new node
new_node = new Node;
cout << "Enter a number: ";
cin >> input_num;
new_node->num = input_num;
new_node->next = NULL;
// Case when first node is added to list, i.e. the when list is empty
if(*head == NULL)
{
*head = new_node;
}
// Otherwise
else
{
Node *temp = *head;
// Iterate to the last node in list
while(temp->next != NULL)
temp = temp->next;
// Add the new node to the list
temp->next = new_node;
}
return 0;
}
/*
Function to calculate the average of the nodes
Arguments:
*head -> pointer to the first node in the list
Return value:
The average of the nodes in the list.
*/
double avgNodes(Node *head)
{
int count = 0; // Variable to store the count of nodes
double sum = 0; // Variable to store the sum of nodes
while(head != NULL)
{
++count;
sum += head->num;
head = head->next;
}
// Calculating the average
double avg = (double)sum / count;
return avg;
}
/*
Function to print the list
Arguments:
*head -> Pointer to the first node in the list
*/
int printList(Node *head)
{
cout << "The list is:" << endl;
while(head != NULL)
{
cout << head->num << " -> ";
head = head->next;
}
cout << "NULL" << endl;
return 0;
}
/*
Driver function
*/
int main()
{
Node *first = NULL;
int choice, count;
double avg;
// Displaying the options available to the user
cout << "MENU" << endl;
cout << "1. Add node" << endl;
cout << "2. Average of list" << endl;
cout << "3. Print the list" << endl;
cout << "4. Exit" << endl;
do
{
// Take choice from user
cout << "Enter your choice: ";
cin >> choice;
// Do task according to the choice
switch(choice)
{
case 1:
addNode(&first);
break;
case 2:
avg = avgNodes(first);
cout << "Average of list: " << avg << endl;
break;
case 3:
printList(first);
break;
case 4:
cout << "Bye!!" << endl;
break;
default:
cout << "Sorry!! No such choice. Please try again." << endl;
}
}while(choice != 4);
return 0;
}
The output for the program is:
Answer 3
Now let's analyze the time complexity of countNode() and avgNodes().
For countNode():
We travel the whole list once to increase the count in eaach iteration. That means we iterate n times over a list of n nodes.
Hence, time complexity of countNode() is O(N).
For avgNodes():
We travel the whole list once to add each element to the variable sum, and increase count in each iteration. That means we iterate n times over a list of n nodes.
Hence, time complexity of avgNodes() is O(N).
Answer 4
In this, we want to enter node at a specified location.
For this, we first take a real number from the user and create a new_node using that. Then we ask the user for the position in which we want to insert this new_node.
If the postion entered by user can be access (either it already exist, or it is just one above the count of nodes (case when we insert at end of list)):
The complete code for this is:
#include <iostream>
using namespace std;
/*
Defining the structure for Node
*/
struct Node
{
double num; // To store the real number
Node *next; // To store pointer to next node
};
/*
Function to add a node to the list
Arguments:
**head -> Double pointer to the first node of the list
*/
int addNode(Node **head)
{
Node *new_node = NULL; // The new node
double input_num; // Get the real number from user
// Defining the new node
new_node = new Node;
cout << "Enter a number: ";
cin >> input_num;
new_node->num = input_num;
new_node->next = NULL;
// Case when first node is added to list, i.e. the when list is empty
if(*head == NULL)
{
*head = new_node;
}
// Otherwise
else
{
Node *temp = *head;
// Iterate to the last node in list
while(temp->next != NULL)
temp = temp->next;
// Add the new node to the list
temp->next = new_node;
}
return 0;
}
/*
Function to count the number of nodes in the list
Arguments:
*head -> pointer to the first node in the list
Return value:
The count of nodes in the list.
*/
int countNode(Node *head)
{
int count = 0;
// Iterating the entire list
while(head != NULL)
{
// Increasing the count of nodes by one in each iteration
++count;
head = head->next;
}
return count;
}
/*
Function to add a node at position given by user
*/
int addNodeAtPosition(Node **head)
{
Node *new_node = NULL; // The new node
double input_num; // Get the real number from the user
int position; // Get the position from the user
// Defining the new node
new_node = new Node;
cout << "Enter a number: ";
cin >> input_num;
new_node->num = input_num;
new_node->next = NULL;
// Taking the position of insertion from the user
cout << "Enter the position of the node: ";
cin >> position;
// Checking if insertion at given position feasible or not.
if(position > countNode(*head) + 1)
{
cout << "Sorry!! Node cannot be entered at this position. List is too short." << endl;
return 0;
}
// Inserting the node
else
{
// If we insert at the start of the list
if(position == 1)
{
new_node->next = *head;
*head = new_node;
}
// Otherwise
else
{
int counter = 1; // Keep track of the current position
Node *temp = *head;
// Iterate the list to reach node at (position-1)
while(temp != NULL && counter < position-1)
{
++counter;
temp = temp->next;
}
// Insert the node at position
new_node->next = temp->next;
temp->next = new_node;
}
}
return 0;
}
/*
Function to print the list
Arguments:
*head -> Pointer to the first node in the list
*/
int printList(Node *head)
{
cout << "The list is:" << endl;
while(head != NULL)
{
cout << head->num << " -> ";
head = head->next;
}
cout << "NULL" << endl;
return 0;
}
/*
Driver function
*/
int main()
{
Node *first = NULL;
int choice, count;
double avg;
// Displaying the options available to the user
cout << "MENU" << endl;
cout << "1. Add node" << endl;
cout << "2. Add node at nth position" << endl;
cout << "3. Print the list" << endl;
cout << "4. Exit" << endl;
do
{
// Take choice from user
cout << "Enter your choice: ";
cin >> choice;
// Do task according to the choice
switch(choice)
{
case 1:
addNode(&first);
break;
case 2:
addNodeAtPosition(&first);
break;
case 3:
printList(first);
break;
case 4:
cout << "Bye!!" << endl;
break;
default:
cout << "Sorry!! No such choice. Please try again." << endl;
}
}while(choice != 4);
return 0;
}
The output of the program is:
Answer 5
In this, we want to delete node from position specified by the user. To do this, we first take the position from the user. We declare a variable del_node to store reference to the node. C++ do not have garbage collector, hence we manually need to free the memory. Then we check, if deletion is poosible from that position or not.
Here is the complete code for this question:
#include <iostream>
using namespace std;
/*
Defining the structure for Node
*/
struct Node
{
double num; // To store the real number
Node *next; // To store pointer to next node
};
/*
Function to add a node to the list
Arguments:
**head -> Double pointer to the first node of the list
*/
int addNode(Node **head)
{
Node *new_node = NULL; // The new node
double input_num; // Get the real number from user
// Defining the new node
new_node = new Node;
cout << "Enter a number: ";
cin >> input_num;
new_node->num = input_num;
new_node->next = NULL;
// Case when first node is added to list, i.e. the when list is empty
if(*head == NULL)
{
*head = new_node;
}
// Otherwise
else
{
Node *temp = *head;
// Iterate to the last node in list
while(temp->next != NULL)
temp = temp->next;
// Add the new node to the list
temp->next = new_node;
}
return 0;
}
/*
Function to count the number of nodes in the list
Arguments:
*head -> pointer to the first node in the list
Return value:
The count of nodes in the list.
*/
int countNode(Node *head)
{
int count = 0;
// Iterating the entire list
while(head != NULL)
{
// Increasing the count of nodes by one in each iteration
++count;
head = head->next;
}
return count;
}
/*
Function to delete a node from specified position in the list
Arguments:
**head -> Double pointer for he first node of the list
*/
int deleteNode(Node **head)
{
int position; // Get position for deleting from the user
cout << "Enter the position of node to be deleted: ";
cin >> position;
// Taking the position of insertion from the user
if(position > countNode(*head))
{
cout << "Sorry!! Node cannot be entered at this position. List is too short." << endl;
return 0;
}
// Checking if insertion at given position feasible or not.
else
{
Node *del_node = NULL; // Node to be deleted
// If we are deleting the first node of the list
if(position == 1)
{
del_node = *head;
*head = (*head)->next;
}
// Otherwise
else
{
int counter = 1; // Keep track of the current position
Node *temp = *head;
// Iterate the list to reach node at (position-1)
while(temp != NULL && counter < position-1)
{
++counter;
temp = temp->next;
}
// Delete node from the position
del_node = temp->next;
temp->next = temp->next->next;
}
// Freeing the memory allocated to the deleted node
free(del_node);
}
return 0;
}
/*
Function to print the list
Arguments:
*head -> Pointer to the first node in the list
*/
int printList(Node *head)
{
cout << "The list is:" << endl;
while(head != NULL)
{
cout << head->num << " -> ";
head = head->next;
}
cout << "NULL" << endl;
return 0;
}
/*
Driver function
*/
int main()
{
Node *first = NULL;
int choice, count;
double avg;
// Displaying the options available to the user
cout << "MENU" << endl;
cout << "1. Add node" << endl;
cout << "2. Delete a node" << endl;
cout << "3. Print the list" << endl;
cout << "4. Exit" << endl;
do
{
// Take choice from user
cout << "Enter your choice: ";
cin >> choice;
// Do task according to the choice
switch(choice)
{
case 1:
addNode(&first);
break;
case 2:
deleteNode(&first);
break;
case 3:
printList(first);
break;
case 4:
cout << "Bye!!" << endl;
break;
default:
cout << "Sorry!! No such choice. Please try again." << endl;
}
}while(choice != 4);
return 0;
}
The output for the program is:
Hope my answer meet your needs.