Objective: Learning linked list... C++ ===> (Using Structures) Problem Specifica
ID: 3675374 • Letter: O
Question
Objective: Learning linked list... C++ ===> (Using Structures)
Problem Specification:
An employer would like to maintain a linked list for employees, the data stored is an employee
number (a positive integer), and a yearly salary (a float). Would like you as the programmer to
define the required classes in header files, and the methods in implementation files.
The methods used are:
Insert: Which inserts elements at the beginning of the list, which is the most recent input
is at the beginning of the list.
Remove: which deletes the last element in the list.
Display: a recursive function that prints the elements of the list, last to first.
Clear: a function that deletes every node from the list and leaves the list empty.
Criteria:
Menu is used to display options and calls methods.
Guards are used.
insert performs its task correctly.
remove performs its task correctly.
display performs it task correctly.
display is recursive.
clear performs it task correctly.
Explanation / Answer
Please find the required program below :
#include <iostream>
using namespace std;
struct Emp {
int num;
float salary;
Emp* next;
};
// only for the 1st Node
void initEmp(struct Emp *head,int n, float s){
head->num = n;
head->salary = s;
head->next =NULL;
}
void insert(struct Emp **head, int n,float s) {
Emp *newEmp = new Emp;
newEmp->num = n;
newEmp->salary = s;
newEmp->next = *head;
*head = newEmp;
}
void remove(struct Emp **head) {
Emp *cur = *head;
Emp *t = NULL;
while(cur->next != NULL) {
t = cur;
cur = cur->next;
}
t->next = NULL;
delete cur;
}
void clear(struct Emp **node)
{
struct Emp *tmpEmp;
while(*node) {
tmpEmp = *node;
*node = tmpEmp->next;
delete tmpEmp;
}
}
void display(struct Emp *head) {
Emp *list = head;
while(list) {
cout << list->num << " ";
cout << list->salary << " ";
list = list->next;
}
cout << endl;
}
void printMenu(){
cout << "Please chose an option : " << endl;
cout << "0) Exit" << endl;
cout << "1) Add employee" << endl;
cout << "2) Remove employee" << endl;
cout << "3) Diplay All" << endl;
cout << "4) Clear All" << endl;
}
int main()
{
struct Emp *head = NULL;
int c;
while(true){
printMenu();
cin >> c;
if(c==0)
break;
else if(c==1){
int n;
float s;
cout << "Enter employee number and salary :"<<endl;
cin >> n;
cin >> s;
if(head==NULL){
head = new Emp;
initEmp(head,n,s);
}else{
insert(&head,n,s);
}
cout << "Insert done" << endl;
}else if(c==2){
remove(&head);
cout << "Remove done" << endl;
}else if(c==3){
display(head);
}else if(c==4){
clear(&head);
cout << "Clear done" << endl;
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.