Write a merge function based on the following conditions and sample Code: #inclu
ID: 3732862 • Letter: W
Question
Write a merge function based on the following conditions and sample Code:
#include
//exception is thrown if wrong input
class BadInput {
public:
BadInput (){};
};
template
struct Node {
E data;
Node *next;
};
template
class SortedChain {
public:
SortedChain() {first=0;}
~SortedChain();
bool IsEmpty() {return (first==0);}
//int Length() const;
//bool Search (const K& k, const E& e);
SortedChain& Delete(const K& k, E& e);
SortedChain& Insert (const K& k,const E& e);
void Output() const;
private:
Node *first;
};
template
SortedChain::~SortedChain()
{
Node *current=first;
while (first)
{ current=first->next;
delete first;
first=current;
}
}
template
SortedChain& SortedChain::Delete(const K& k, E& e)
{
Node *prior=first, *current=first;
while (current && current->data.Key() < k){ //search until key=k or key > k
prior=current;
current=current->next;
}
if (current && current->data.Key() == k) { //
e=current->data;
if (first == current) //delete first node
first=current->next;
else
prior->next=current->next;
delete current;
return *this;
}
else
throw BadInput();
}
SortedChain& SortedChain:: Merge (SortedChain & S2 const) {
------- write your function
}
template
SortedChain& SortedChain::Insert(const K& k, const E& e)
{
Node *prior=first, *current=first;
while (current && (current->data).Key() < k){
prior=current;
current=current->next;
}
if (current && (current->data).Key() == k)
throw BadInput(); //another node with same key
else {
Node *newp;
newp=new Node;
if (first == current) { //we like to insert on first position
first=newp;
}
else
prior->next=newp;
newp->next = current;
newp->data=e;
return *this;
}
}
template
void SortedChain::Output() const
{
Node *current=first;
cout << endl;
while (current) {
cout << current->data.Key() << current->data.Value() << " ->";
current=current->next;
}
}
class TypeE {
public:
long key;
long value;
Type(){};
long Key(){return key;}
long Value(){return value;}
};
main()
{
try {
SortedChain Chain;
TypeE e;
e.key=2;
e.value = 1000;
Chain.Insert(e.Key(),e);
e.key=4;
e.value =500;
Chain.Insert(e.Key(),e);
e.key=6;
e.value =1500;
Chain.Insert(e.Key(),e);
e.key=1;
e.value=3000;
Chain.Insert(e.Key(),e);
Chain.Output();
Chain.Delete(2,e);
Chain.Output();
}
catch (BadInput) {
cerr << endl << "Bad Input";
}
}
Explanation / Answer
here is your function : ------------>>>>>>>>>
SortedChain<E,K>& SortedChain<E,K>:: Merge (SortedChain<E,K> & S2 const) {
if(s2.first == NULL){
return *this;
}
Node *temp = s2.first;
while(temp != NULL){
insert((temp->data).Key(),temp->data);
}
return *this;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.