=========================preview======================
(COMP152)[2011](s)midterm~3319^_79572.pdf
Back to COMP152 Login to download
======================================================
COMP 152 Spring 2011
Midterm Solutions
1. (a) void SortedList::insertNode(int item){ Node* newp, * cur, * pre; newp = new Node; newp->data = item;
pre = NULL;
cur = this->head;
while( (cur != NULL) && (item>cur->data)){

pre = cur;
cur = cur->next;
}

if(pre == NULL){
newp->next = head;
head = newp;

} else {
pre->next = newp;
newp->next = cur;

}
}

(b) void SortedList::merge(const SortedList& inList){ Node* ptr = inList.head; while (ptr != NULL){
this->insertNode(ptr->data);
ptr = ptr->next;
}
}

1

(c) void SortedList::split(SortedList& outList){ Node* fast, * slow; if (this->head==NULL || this->head->next==NULL)
outList.head = NULL;

else {
slow = this->head;
fast = this->head->next;
while (fast != NULL) {

fast = fast->next;
slow = slow->next;
if (fast != NULL) {

fast = fast->next;
}

}
outList.head = slow->next;
slow->next = NULL;
}

}

2. (a) Matrix::Matrix(int n, int r, int c){
numRows = r;
numColumns = c;
elements = new int*[numRows];
for(int i=0;i<numRows;i++){
elements[i] = new int[numColumns];
for(int j=0;j<numColumns;j++)
elements[i][j] = n;
}
}
(b) Matrix::Matrix(const char* filename){
ifstream fin(filename);
//if the file is not opened successfully, create an empty matrix
if (!fin.is_open()){
exit(-1);
}
//read the numRows and numColumns (first line)
fin >> numRows >> numColumns;
//load the matrix
elements = new int*[numRows];
for(int i=0;i<numRows;i++){
elements[i] = new int[numColumns];
for(int j=0;j<numColumns;j++)
fin >> elements[i][j];
}
//remember to close the file after all the file I/O
fin.close();
}

(c) Matrix::Matrix(const Matrix& anotherMatrix){ numRows = anotherMatrix.numRows; numColumns = anotherMatrix.numColumns;
elements = new int*[numRows];

for(int i=0;i<numRows;i++){
elements[i] = new int[numColumns];
for(int j=0;j<numColumns;j++)

elements[i][j] = anotherMatrix.elements[i][j];
}
}

(d) void Matrix::makeEmpty(){ if(elements != NULL){ for(int i=0;i<numRows;i++){ delete [] elements[i]; } delete [] elements;
}

elements = NULL;
numRows = 0;
numColumns = 0;

}

(e) int& Matrix::element(int i, int j){
return elements[i][j];
}

(f ) const int& Matrix::element(int i, int j) const{
return elements[i][j];
}

(g) const Matrix& Matrix::operator=(const Matrix& anotherMatrix){
if(this == &anotherMatrix)
return *this;

makeEmpty();

numRows = anotherMatrix.numRows;
numColumns = anotherMatrix.numColumns;
elements = new int*[numRows];
for(int i=0;i<numRows;i++){

elements[i] = new int[numColumns];
for(int j=0;j<numColumns;j++)

elements[i][j] = anotherMatrix.elements[i][j];
}
return *this;

}

(h) Matrix Matrix::operator+(const Matrix& anotherMatrix) const{ if(numRows != anotherMatrix.numRows ||
numColumns != anotherMatrix.numColumns)
exit(-1);

Matrix result(0, numRows, numColumns);
for(int i=0;i<numRows;i++){
for(i