C++ Write a main program that creates a linked list object and tests all the cla
ID: 3694460 • Letter: C
Question
C++
Write a main program that creates a linked list object and tests all the class methods. The destructor needs to go down the list of links deleting each one. Remember to get the pointer to the next link before deleting a link. Although executing delete p; p = p->next will often work, it is asking for trouble, as p has been deleted before p->next is accessed. The copy constructor needs to create a new collection of links and copy the original link data. Note that you can use the addLast method to create the new list.
The assignment overload needs to:
1 check for self assignment
2 delete existing storage on LHS of =
3 copy RHS of = to LHS
Explanation / Answer
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include<iostream>
#include <stdexcept>
using namespace std;
class node
{
public:
int info;
node *link;
node()
{
link=NULL;
}
node(int info)
{
this->info=info;
link=NULL;
}
};
class LinkedList
{
public:
LinkedList();//constructor
LinkedList(const LinkedList List);//constructor
void addFirst(int info);
void addLast(int info);
int removeFirst() ;
int delete_back()
void printList();
private:
node *head, *tail;
int size;
};
LinkedList::LinkedList()
{
head=tail=NULL;
size=0;
}
LinkedList::LinkedList( const LinkedList &v )
{
node * p1 = 0;//current
node * p2 = 0;//link
if( v.head == 0 )
head = 0;
else
{
head = new node;
head -> info = v.head -> info;
p1 = head;
p2 = v.head -> link;
}
while( p2 )
{
p1 -> link = new node;
p1 = p1 -> link;
p1 -> info = p2 -> info;
p2 = p2 -> link;
}
p1 -> link = 0;
}
void LinkedList::addFirst(int info)
{
node *newNode=new node(info);
newNode->link = head;
head=newNode;
size++;
if(tail==NULL)
tail=head;
}
void LinkedList::addLast(int info)
{
if(tail==NULL)
{
head=tail=new node(info);
}
else
{
tail->link=new node(info);
}
size++;
}
int LinkedList::removeFirst()
{
if(size==0)
cout<<"no node inside";
else
{
node *temp= head;
head = head->link;
size--;
if(head==NULL)tail=NULL;
int info=temp->info;
delete temp;
return info;
}
}
int LinkedList::delete_back(){
if(head != NULL){
node *end = head;
if(end->link != NULL){
node *prev_end;
while(end->link != NULL){
prev_end = end;
end = end->link;
}
prev_end->link = NULL;
delete end;
}
else {
delete head;
head = NULL;
}
size--;
}
return prev_end;
}
void LinkedList::printList()
{
node *current=head;
while(current!=NULL)
{
cout<<current->info;
current = current->link;
}
}
#endif
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.