Create a simple linked list that stores the following list of information: COMP104 (Name of the List) stName: 1 stNo: 1111 stName: 2 stNo: 2222 stName: 3 stNo: 3333 stName: 4 stNo: 4444


Provided the program for above given information with appropriate comments as shown below. Also attached the snapshot of result generated after executing the below given C++ program as shown in the below attached snapshot.
C++ Program :
#include <iostream>
using namespace std;
// A linked list named as COMP104
class COMP104
{
public:
string stName;
int stNo;
COMP104 *next;
};
/* This function Given a reference to the head of a list,
a string name and an int, inserts a new node at the end */
void insert(COMP104** head_ref, string stname, int stno)
{
/* Allocating the node */
COMP104* node = new COMP104();
COMP104 *last = *head_ref;
/* putting the data into list */
node->stName = stname;
node->stNo = stno;
/* This new node is going to be the last node, so make next of it as NULL*/
node->next = NULL;
/* If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = node;
return;
}
/* Traverse till the last node */
while (last->next != NULL)
last = last->next;
/* Change the next of last node */
last->next = node;
return;
}
//This function traverse through the list and prints it.
void printList(COMP104 *node)
{
while (node != NULL)
{
cout<<"stName:"<<node->stName <<endl << "stNo:"<<node->stNo << endl << endl;
node = node->next;
}
}
int main()
{
/* Start with the empty list */
COMP104* head = NULL;
// Inserting stName = 1 and stNo = 1111 in linked list.
insert(&head, "1", 1111);
// Inserting stName = 2 and stNo = 2222 in linked list.
insert(&head, "2", 2222);
// Inserting stName = 3 and stNo = 3333 in linked list.
insert(&head, "3", 3333);
// Inserting stName = 4 and stNo = 4444 in linked list.
insert(&head, "4", 4444);
cout<<"Created Linked list is as below: " << endl << endl;
printList(head);
return 0;
}
Step by step
Solved in 2 steps with 1 images









