Question 2. Linked Lists [9]
The table below shows a program and the output we would see if
we attempted to run it.
Identify why the segmentation fault occurs
and provide an appropriate fix. (Only a one-line change is needed.)
#include <iostream>
using namespace std;
class list {
public:
list(); // create an empty list
~list(); // delete all remaining nodes
void insert(int v); // insert v at front of list
void remove(); // remove/discard back list node
void print(); // display list contents
private:
struct node {
int value;
node *next;
} *Lptr; // Lptr tracks the front of the list
};
int main() {
list L;
L.insert(1);
L.insert(2);
L.print();
L.remove();
L.print();
}
void list::insert(int v) {
node *n = new node();
if (n != NULL) {
n->value = v;
n->next = Lptr;
Lptr = n;
}
}
|
list::list() {
Lptr = NULL;
}
list::~list() {
while (Lptr != NULL) remove();
}
void list::print() {
node *n = Lptr;
cout << "List contents: ";
while (n != NULL) {
cout << n->value;
n = n->next;
if (n != NULL) cout << ", ";
else cout << "." << endl;
}
}
void list::remove() {
if (Lptr == NULL) return;
if (Lptr->next == NULL) {
delete Lptr;
Lptr = NULL;
}
node *n = Lptr;
node *prev = NULL;
while (n->next != NULL) {
prev = n;
n = n->next;
}
delete n;
prev->next = NULL;
} |
// resulting output List contents: 2, 1. List contents: 2. Segmentation fault | |