Search code examples
c++stacknodesinsertion

Insert the node before the specified element


I have Stack, and i need to insert the node before the specified element, and this code works, but i need code without count and count1, because sorting doesn't work. Can you help me remake the code? I tried to do something with code, but it's doesn't work

void Stack::stackA(Item *q,Item *q1) // q - specified element, q1 - new element
{

int count=0;
int count1=0;
for (Item *i=this->first;i;i=i->next) 
{   
    count++;
    if (*i == *q)  // Here we find position of the specified element
        break;
}


for (Item *i=this->first;i;i=i->next)
{

    Item *temp=new Item(*q1);

    if(*this->first == *q)  // if element first
    {
        this->first=temp;
        temp->next=i;
        break;
    }
    if (count1+1==count-1) //count-1,insert before specified element
    {
          if(i->next)
            temp->next=i->next;
          else
            temp->next=0;
          i->next=temp;
    }
    count1++;
}
}

Solution

  • The goal here is to find the node before q, set its next to q1, then set q1->next to q

    void Stack::stackA(Item *q,Item *q1) // q - specified element, q1 - new element
    {
        Item* item = this->first;
        if (item == q) {
            this->first = q1;
            q1->next = q;
            return;
        }
        while (item != null) {
            if (item->next == q) {
                item->next = q1;
                q1->next = q;
                break;
            }
            item = item->next;
        }
    }
    

    Update: Handled the case if q is the first item.