【问题标题】:Insert the node before the specified element在指定元素之前插入节点
【发布时间】:2012-11-23 23:18:27
【问题描述】:

我有堆栈,我需要在指定元素之前插入节点,这段代码可以工作,但我需要没有 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++;
}
}

【问题讨论】:

  • 你为什么使用自定义单链表(容易出错)而不是 std::stack?

标签: c++ stack nodes insertion


【解决方案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 是第一项,则处理这种情况。

【讨论】:

  • 它可以工作,但我在指定元素后失去了连接
  • 失去连接是什么意思?我刚刚修复了代码来处理 q 是列表中第一项的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多