Building and Working with a Simple Linked List. Write a program that builds a si
ID: 3690194 • Letter: B
Question
Building and Working with a Simple Linked List. Write a program that builds a simple linked list containing integers from 0 to 20. The program then prints out the contents of the linked list to the screen in ascending order. It also adds the contents of all the nodes in the list and prints out the sum total at the bottom. The output functionality must be in a separate programmerdefined function and it must receive a pointer that points to the head of the list. The output should look as follows:
Node #0 contains 0
Node #1 contains 1
Node #2 contains 2
. . .
Node #20 contains 20
The sum total of all nodes in this list is:
Explanation / Answer
source code of the linked list :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class linkedlist
{
private:
struct node
{
int data;
node *link;
}*start;
public: linkedlist()
{
start=new node;
start->link=NULL;
start->data=0;
}
~ linkedlist();
void create();
void display();
void sort();
void sum();
};
linkedlist :: ~linkedlist()
{
node *current;
while(start!=NULL)
{
current=start->link;
delete current;
start=current;
}
}
void linkedlist :: create()
{
node *current;
int i;
for(i=0;i<=20;i++)
{
current=new node ;
current->link=start->link;
current->data=i;
start->link=current;
}
}
void linkedlist :: display()
{
node *current;
cout<<" original elements in the list ";
for(current=start->link;current;current=current->link)
cout<<current->data<<" ";
}
void linkedlist :: sort()
{
int i,j,k,cur;
node *q,*r,*current;
for(i=0;i<=20-1;i++)
{
q=start;
r=q->link;
for(j=0;j<=(20-i);j++)
{
if(q->data>r->data)
{
cur=q->data;
q->data=r->data;
r->data=cur;
}
q=q->link;
r=r->link;
}
}
cout<<" sorted elements in the list ";
for(current=start->link;current;current=current->link)
cout<<current->data<<" ";
}
void linkedlist::sum()
{
int sum=0;
node *current;
for(current=start->link;current;current=current->link)
{
sum=sum+current->data;
}
cout<<" sum of the elements in the list = "<<sum;
}
void main()
{
linkedlist ll;
clrscr();
ll.create();
ll.display();
ll.sort();
ll.sum();
getch();
return;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.