Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m trying to add an item to the end of a linked list. I\'ve tried a few differ

ID: 3550896 • Letter: I

Question

I'm trying to add an item to the end of a linked list.  I've tried a few different methods and none have worked.  this is what i have right now.  My main difficulty is traversing the linked list to find tail.  If i can properly do that, i think i can do the rest.  




  


#include <iostream>
using namespace std;

class node
{
public:
    int data;
    node *next;
};

class linkedList
{
private:
    node* ptrHead;
    node* ptrTail;
    int size;

public:
    linkedList();  //default constructor
    void display();
    void addFront(int);
    void removeFront();
    void addBack(int);
    void removeBack();

};


/finished
linkedList::linkedList(){
    size = 0;
    ptrHead = ptrTail = NULL;
}


//finished
void linkedList::display(){
    node* pCurrent = ptrHead;
    
    while (pCurrent != NULL) {
        cout << pCurrent->data << " "; //display current item
        pCurrent = pCurrent->next; //move to next item
    }
    cout << size;
}


//finished
void linkedList::addFront(int addData){
   
    node* n = new node;
    n->next = ptrHead;
    n->data = addData;
    ptrHead = n;
    
    size++;
}


//finished
void linkedList::removeFront(){
    
    node* n = ptrHead;
    ptrHead = ptrHead->next;
    delete n;
    
    size--;
}


//////////////////////////////////////////  ADD TO BACK OF LIST ///////////////////////////////////////////////////////

void linkedList::addBack(int addData){   ////work in progress

    node* n = new node; //create new node
    n->data = addData;  //input data
    n->next = NULL;     //set node to point to NULL
    


////////////////////////////////TRAVERSE LINKED LIST TO FIND TAIL
//find tail
    node* pCurrent = ptrHead;
    while (pCurrent != NULL)
        pCurrent = pCurrent->next;
    
    if (pCurrent->next == NULL) {
        pCurrent->next == ptrTail;
    }

////////////////////////////////  
    
    
    
    //tail points to new node
    ptrTail->next = n;
    
    //new node is now tail;
    n = ptrTail;
    
    //increment size
    size++;
    
}


Explanation / Answer

It seems that your code almost does it.

void linkedList::addBack(int addData)

void List::insert_end(int number)
{
node *p=new node;
p->info=addData;
p->next=NULL;
node *t=ptrHead;
if ( t != NULL )
{
for (; t->next != NULL; t=t->next)
{
}
}
if(ptrHead==NULL)
{

p->next=ptrHead;
ptrHead=p;
}
else
{
t=p;
p->next=t->next;
}
}