Lab Assignment #6 Solution

$30.00

Description

Begin by making a new directory for this lab, and then open a file called, list1.h. Into this file type the following code:

#include<iostream>

#include<string>

struct Node{

std::string data;

Node *link;

};

class Lilist{

public:

Lilist(){head = NULL;}

void add(std::string item);

void show();

private:

Node *head;

};

void Lilist::add(std::string item){

Node * tmp;

if(head == NULL){

head = new Node;

head -> data = item;

head -> link = NULL;

}

else{

for(tmp = head; tmp->link != NULL; tmp = tmp -> link)

; // this loop simply advances the pointer to last node in

//the list

tmp ->link = new Node;

tmp = tmp->link;

tmp->data = item;

tmp->link = NULL;

}

}

void Lilist::show(){

for(Node *tmp = head; tmp != NULL; tmp = tmp->link)

std::cout<<tmp->data<<” “;

}

I know that you could just copy-paste, but I’m hoping that you will learn how this works by typing in the code yourself.

Now write a main that looks like this in a file called main.cc

#include<iostream>

#include<string>

#include “list1.h”

using namespace std;

int main(){

Lilist L1, L2;

string target;

L1.add(“Charlie”);

L1.add(“Lisa”);

L1.add(“Drew”);

L1.add(“Derrick”);

L1.add(“AJ”);

L1.add(“Bojian”);

cout<<“Now showing list One:\n”;

L1.show();

// END OF PART ONE

// The code from here down requires that you add two functions to
//the class

/*

cout<<”Enter a name to search:”;

cin>>target;

if(L1.search(target) != NULL)

cout<<”That name is stored at address: “<<L1.search(target) <<endl;

else

cout<<”That name is not in the list.\n”;

L1.move_front_to_back();

L1.move_front_to_back();

L1.show();

*/

return 0;

}

After you have written and run the program down to the place where it says End of Part One, go back into your class, and write a search function that takes a string as its argument. It will return the address of the node holding the string, or Null if the pointer runs off the end of the list. Hint, part of this code will include:
if(cursor->data == target) return cursor;

Then write a move_front_to_back function. The key here is to use an extra pointer to hold the first node in the list, then move the head to the second node of the list, and then with still another pointer find the last node in the list and hook the node that used to be at the front to the back. (Look at the code you’ve written for adding nodes.) Uncomment the parts of main

When you are done run the program with a script file:

script myresults

a.out

ctrl-d

This file will show the list printed both in its original order and in the order with the first two names moved to the back of the list. Submit this script file along with your two source code files to Blackboard.