Hello every1 , just want to ask for a clear explanation about the loop after the else inside the "add" and "remove" function ..
any1 can explain to me what does these for loop do actually in the linked list ? :
"add" n "remove" after the else :
// for ( int i = 0 ; i < position - 2 ; i++ )
// for ( int i = 0 ; i < position - 2 ; i++ )
*i'm not asking for alternative codes , i just want to know what r these for loop do actually , i really don't understand ..
Player::~Player()
{
while (!isEmpty()) // remove all node in the list
{
remove(1);
}
}
ListItemType Player::retrieve ( int position ) const // Retrieve an item from the list at a given position
{
if ( position >= 1 && position <= size )
{
Node *ptr = head;
for ( int i = 0 ; i < position - 1 ; i++ )
{
ptr = ptr->next;
}
return ptr->item;
}
}
void Player::add ( int position , ListItemType newItem ) // insert a new item into the list at a given position
{
if ( position >= 1 && position <= size+1 )
{
// create a new node to store the new item
Node *newNode = new Node;
newNode->item = newItem;
if ( position == 1 )
{ // insert the new node at the beginning of list
newNode->next = head;
head = newNode;
}
else
{
// insert the new node at the middle or end of list
Node *ptr = head;
for ( int i = 0 ; i < position - 2 ; i++ )
{
ptr = ptr->next;
}
void Player::remove ( int position ) // remove an item in the list at a given position
{
if ( position >= 1 && position <= size )
{
if ( position == 1 ) // remove the first node in the list
{
Node *ptr = head;
head = head->next;
delete ptr;
ptr = NULL;
}
else
{ // remove a node, which is not the first node, in the list
Node *ptr = head;
for ( int i = 0 ; i < position - 2 ; i++ )
{
ptr = ptr->next;
}
ListItemType retrieve ( int position ) const;
void add ( int position , ListItemType newItem );
void remove ( int position );
bool isEmpty() const;
void show();
int getLength() const;
};
Well, the developer of this code determined that position 1 is before the head. In the else branch of add/remove ptr->next; means (without a single iteration of the loop) it is alread at position 2.
In other words: Since the process skips two elements you need - 2 in the break condition of the loop.