IN C++ struct dlist_node { char contents; // contents in the node dlist_node *ba
ID: 3578712 • Letter: I
Question
IN C++
struct dlist_node
{
char contents; // contents in the node
dlist_node *back, // pointer to previous node in the list
*next; // pointer to the next node in the list
};
typedef dlist_node* dptr;
class dlist
{
private:
dptr front, // pointer to the front of the list
current; // pointer to current node in the list
public:
dlist (); // constructor creates an empty list
void insert (char ch); // inserts a new node
void remove (); // removes a node
void Move_Right(int distance); // moves current right
void Move_Left(int distance); // moves current left
void print (); // prints the list
};
The public functions that you need to define are:
dlist (): Constructor that initializes the list to be empty.
void insert (char ch): Adds a new node to the right of current containing ch and points current at the new node. Should insert first node correctly.
void remove (): Removes the node from the list pointed to by current. Points current at the node after the deleted node (if present) else points current at the node before the deleted node (if present). Should remove last node correctly and recycle nodes. Should not fail if list is empty.
void Move_Right (int distance): Moves current to the right distance nodes. If the given distance will move current off the end of the list, current should be set to point at the rightmost node. Should not fail if list is empty.
void Move_Left (int distance): Moves current to the left distance nodes. If the given distance will move current off the end of the list, current should be set to point at the leftmost node. Should not fail if list is empty.
void print (): Prints all the nodes in the list. The value pointed to by current should be printed in braces.print does not output any spaces or linefeeds. For example, if the data in the linklist represents ISP 658, the output would be :
ISP 6{5}8
Explanation / Answer
Partial solution as per policy.
dlist::dlist () { front = NULL; current = NULL; }
void dlist::insert (char ch) {
dptr newNode = new dlist_node();
newNode->contents = ch;
newNode->back = NULL;
newNode->next = NULL;
if(front == NULL) {
front = newNode; current = newNode;
} else {
current->next = newNode;
newNode->back = current;
} }
void dlist::print() {
dptr pNode = front;
while(pNode != NULL) {
if(pNode != current) cout << pNode->contents;
else cout<<"{"<<pNode->contents<<"}";
pNode = pNode->next;
}
}