Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在指定元素之前插入节点_C++_Stack_Nodes_Insertion - Fatal编程技术网

C++ 在指定元素之前插入节点

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

这里的目标是找到
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
是第一项,则处理该情况。

为什么使用自定义单链表(容易出错)而不是std::stack?它可以工作,但我在指定元素后失去了连接。失去连接是什么意思?我刚刚修改了代码来处理q是列表中第一项的情况。