13.Define removeFromHead member function of the SLList class as declared in the
ID: 3698703 • Letter: 1
Question
13.Define removeFromHead member function of the SLList class as declared in the Figure 3. The function returns and removes the front/head node from the existing list . Pre-condition - The list should not be empty . Post-condition The head/front node is removed from the list, and the next node is assigned as head. 14.Define removeF romTail member function of the SLList class as declared in the Figure 3. The function returns and removes the rear/tail node from the existing list. . Pre-condition - The list should not be empty Post-condition The tail/rear node is removed from the list, and the previous node is assigned as tail. 15.Define insertAt member function of the SLList class as declared in the Figure - 3. The function inserts a new node with given value passed as the function input in the list at the . Pre-condition The given position input should be valid i.e., a list node should exist at .Post-condition The new node with given value is inserted in the list at the given specified position passed as second function in put. the given position. position. The list is re-organized.Explanation / Answer
Node* removeFromFront()
{
// if list is empty
if(!head)
return;
// point trav to current node
Node *trav = head;
// move to next node
// getNext() return pointer to next node
head = head->getNext();
// if the list is now empty
if( head == NULL )
tail = NULL;
return trav;
}
Node* removeFromTail()
{
// if list is empty
if(!head)
return;
// point trav to current node
Node *trav = head;
// if the list has only 1 node
if( head->getNext() == NULL )
{
head = NULL;
tail = NULL;
}
// loop until we reach the second last node
while(trav->getNext() != tail)
{
// move to next node
// getNext() return pointer to next node
trav = trav->getNext();
}
// point temp to tail;
Node *temp = tail;
// remove the tail
trav->setNext(NULL);
return temp;
}
void insertAt(int value, int position)
{
// create a new node
Node *new_node = new Node(value);
// make new node point to current head
new_node->setNext( head );
// if the list is empty
if(!head)
{
if( position == 0 )
{
// make new_node the new head of the list
head = new_node;
// if the list has only 1 node
if( head->getNext() == NULL )
tail = new_node;
}
else
cout<<"Invalid position.";
}
else
{
int i;
Node *trav = head;
// go to the node previous to the node where we want to insert
for( i = 1 ; i < position ; i++ )
{
// if the list ends
if( !trav )
{
cout<<"Invalid position.";
return;
}
// move to next node
// getNext() return pointer to next node
head = head->getNext();
}
// update the pointers
new_node->setNext(trav->getNext());
trav->setNext(new_node);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.