=========================preview======================
(COMP152)[2010](s)midterm~1980^_10146.pdf
Back to COMP152 Login to download
======================================================
COMP 152 Spring 2010
Midterm Solutions
1. (a) 1020 10 10 20 20
(b) x[3] should not be accessed as x is a dynamic array containing only 3 elements (x[0], x[1], and x[2]). So when i = 3, the access to x[i] is invalid in the loop.
delete [] x; should be used instead of delete x as x is an inte-ger array.
There is a memory leak problem -the reference to the dynamic integer array pointed by the original x is lost in the line x=y;; that integer array can never be freed, thus some memory is leaked
2. (a) Copy constructor:
Ring::Ring()
{
insert_head = NULL;
}
(b) Destructor:
Ring::~Ring()
{
if (insert_head == NULL)
return;
RingNode* del, *del_next;
while (insert_head != insert_head->next)
{
del = insert_head -> next;
del_next = del -> next;
delete del;
insert_head->next = del_next;
}
delete insert_head;
}
(c) Assignment operator:
Ring& Ring::operator=(const Ring& iRing)
{
if ( this == &iRing ) // self-copy
return *this;
// destroy itself
// another ring destruction method
if( insert_head != NULL ){
// at least one node
RingNode *head = insert_head -> next; // new head after ring breaking
RingNode * del; // node to delete
insert_head -> next = NULL; // break the ring to become linear list
del = head;
while( del != NULL ){
head = del -> next;
delete del;
del = head;
}
insert_head = NULL;
}
//then reconstruct ring
RingNode* current_copying_node = iRing.Head();
insert_head = new RingNode(current_copying_node->data);
RingNode* current_node = insert_head;
while (current_copying_node->next != iRing.Head())
{
current_copying_node = current_copying_node->next;
current_node->next = new RingNode(current_copying_node->data);
current_node = current_node->next;
}
current_node->next = insert_head;
return *this;
}
3 (d) Insertion:
Ring& Ring::Insert(const int& i)
{
RingNode* pNode = new RingNode(i);
if (insert_head == NULL)
{
insert_head = pNode;
insert_head->next = insert_head;
return *this;
}
RingNode* current_node = insert_head;
while(current_node->next != insert_head)
{
current_node = current_node->next;
}
current_node->next = pNode;
pNode->next = insert_head;
insert_head = pNode;
return *this;
}
3. (a) void Deque::push_front{const DequeElement& value)
{
frontStack.push(value);
}
(b) void Deque::pop_back()
{
// If the deque is empty, directly return
if (frontStack.empty()&&backStack.empty()) return;
if (!backStack.empty())
{
// If backStack is not empty, directly pop from backStack
backStack.pop();
}
else
{
/* If backStack is empty, first move all elements
from frontStack to backStack */
while(!frontStack.empty())
{
backStack.push(frontStack.top());
frontStack.pop();
}
// Pop from backStack
backStack.pop();
// Move all the remaining elements from backStack to frontStack
while(!backStack.empty())
{
frontStack.push(backStack.top());
bac