0

Stackがあり、指定された要素の前にノードを挿入する必要があります。このコードは機能しますが、並べ替えが機能しないため、countとcount1のないコードが必要です。コードを作り直すのを手伝ってもらえますか?コードで何かしようとしましたが、うまくいきません

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++;
}
}
4

1 に答える 1

1

ここでの目標は、前にノードを見つけ、そのノードをqに設定してnextからq1、に設定q1->nextすることです。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;
    }
}

q更新:が最初の項目である場合にケースを処理しました。

于 2012-11-23T23:25:27.650 に答える