In: Computer Science
Write an array-based implementation of the ADT list that expands the size of the array of list entries as needed so that the list can always accommodate a new entry.
Also reduce the size of the array as needed to accommodate several removals. When the size of the array is greater than 20 and the number of entries in the list is less than half the size of the array, reduce the size of the array so that it is three quarters of its current size.
Note: In expanding the array - when an element is added to a full array, double the size of the array.
IF YOU HAVE ANY DOUBTS COMMENT BELOW I WILL BE THERE TO HELP YOU
ANSWER:
CODE:
#include<iostream>
using namespace std;
//create two function
void insert();
void display();
//initially list size is 4
//total number is the number of items in list
int listSize=4, totalNumber=0;
//pointer to array of list
int * listData;
int main()
{
//ch for choice
int ch;
//initialize pointer of array by list size
listData = new int[listSize];
//drive menu
do
{
cout<<"\n main Menu";
cout<<"\n 1.Insert \n 2.Display\n 3.Exit \n";
cout<<"\n Enter your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
return 0;
break;
}
}
while(true);
return 0;
}
//insert data into list
void insert()
{
//if total number is equal to list size double the size of list array
if(totalNumber==listSize){
cout<<"\nDouble the size of array........\n";
int *newPointer = new int[listSize*2];
for(int i=0;i<listSize;i++){
newPointer[i] = listData[i];
}
listData = newPointer;
listSize = listSize*2;
}
cout<<"Enter element :";
cin>>listData[totalNumber];
totalNumber++;
}
void display()
{
cout<<"\n The Elements of The list ADT are:";
for(int i=0;i<totalNumber;i++)
{
cout<<listData[i]<<" ";
}
}
HOPE IT HELPS YOU
RATE THUMBSUP PLEASE