Create a doubly linked list to store the name and score of 10 players of a match. Perform the following operations on the list
a. Insert the Player information (Name and Score) in the decreasing order of the score to the DLL.
b. To print the Name and Score of the player with the highest score.
SOLUTION FOR THE ABOVE QUESTION
SOLUTION CODE
#include<iostream>
using namespace std;
#include <iostream>
using namespace std;
// A doubly linked list node
struct Node {
int score;
string name;
struct Node* next;
struct Node* prev;
};
//We define a function to insert at the front of the list
void insert_front(struct Node** head, int new_data, string my_name)
{
//allocate memory for New node
struct Node* players_Node = new Node;
//assign data to new node
players_Node->score = new_data;
players_Node->name = my_name;
//new node is head and previous is null, since we are adding at the front
players_Node->next = (*head);
players_Node->prev = NULL;
//previous of head is new node
if ((*head) != NULL)
(*head)->prev = players_Node;
//head points to new node
(*head) = players_Node;
}
// This function prints contents of linked list starting from the given node
void displayList(struct Node* node) {
struct Node* last;
while (node != NULL) {
cout<<"Name: "<<node->name<<", Score: "<<node->score<<endl;
last = node;
node = node->next;
}
if(node == NULL)
cout<<"NULL";
}
//main program
int main() {
/* Start with the empty list */
struct Node* head = NULL;
//Insert the information of the players in a decreasing oreder of the score
insert_front(&head, 10,"kane");
insert_front(&head, 9,"Messi");
insert_front(&head, 8,"silva");
insert_front(&head, 7,"ronaldo");
insert_front(&head, 6,"lukaku");
insert_front(&head, 5,"werner");
insert_front(&head, 4,"reece");
insert_front(&head, 3,"kante");
insert_front(&head, 2,"mendy");
insert_front(&head, 1,"rudiger");
//print the information now
cout<<"\nInformation for 10 players of a match:\n "<<endl;
displayList(head);
return 0;
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment