C++ 在指定元素之前插入节点
我有堆栈,我需要在指定元素之前插入节点,这段代码可以工作,但我需要没有count和count1的代码,因为排序不起作用。你能帮我重做代码吗?我试着用代码做些什么,但它不起作用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) {
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是列表中第一项的情况。