2012-11-23 53 views
0

我有堆棧,並且需要在指定元素之前插入節點,並且此代碼有效,但我需要的代碼不帶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++; 
} 
} 
+0

爲什麼使用自定義單鏈表(這很容易出錯)而不是std :: stack? –

回答

1

這裏的目標是q之前找到節點,設置它的nextq1,然後設置q1->nextq

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是第一項,則處理該案例。

+0

它可以工作,但是我在指定元素後丟失了連接 –

+0

失去連接意味着什麼?我只是修復了代碼來處理q是列表中第一項的情況。 – garbagecollector

相關問題