使用链表进行堆栈弹出操作
Stack pop operation using linked list
列表中的元素是 6495,即前 5 个被推送,然后推送 9,依此类推。现在我想弹出 5(我知道前 6 应该根据 FILO),即以相反的顺序。在我第一次和第二次进行弹出操作时弹出的元素都是 5。Temp 是一个局部变量,所以即使我在 pop 函数中释放它,如果我要在 main 中显示元素,它也不会在 main 中释放?这是真的吗?但无论如何,我在流行操作本身中做了我的 cout,但它仍然不起作用?如果我在弹出后使用显示 fn,它会进入无限循环。
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct stackNode
{
int data;
struct stackNode *next;
};
int is_emp(struct stackNode* head)
{
if(head==NULL)
return 0;
else
return 1;
}
void push(struct stackNode** head,int data)
{
struct stackNode* current =(struct stackNode*)malloc(sizeof(struct stackNode));
current->data=data;
current->next=NULL;
current->next=*head;
*head=current;
}
int pop(struct stackNode** head)
{
int ele;
struct stackNode* temp=*head;
if(is_emp(*head)==NULL)
{
cout<<"Underflow";
return INT_MIN;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
cout<<"Popped ele:"<<temp->data<<endl;
free(temp);
temp=NULL;
}
}
void disp(struct stackNode* head)
{
while(head!=NULL)
{
cout<<head->data<<endl;
head=head->next;
}
}
int main()
{
struct stackNode* head=NULL;
push(&head,5);
push(&head,9);
push(&head,4);
push(&head,6);
disp(head);
pop(&head);
disp(head);
return 0;
}
if(temp!=NULL)
{
ele=temp->data;
temp=temp->next;
}
free(temp);
在这里,您正在使用临时变量而不是头部进行更改。因此,当您在 main 中看到它时,头部指针仍然指向 6。
在头部指针中进行更改,而不是临时指针。
我认为这是您期待的代码。请注意引用的使用。
#include <limits>
struct stackNode
{
stackNode *next;
int data;
stackNode(stackNode *n, int d) : next(n), data(d) {}
};
void push(stackNode* &head,int data)
{
head =new stackNode(head, data);
}
int pop(stackNode* &head)
{
if (head == NULL) {
return std::numeric_limits<int>::min();
} else {
int ret = head -> data;
stackNode *temp = head;
head = head->next;
delete temp;
return ret;
}
}
int main()
{
stackNode* head = NULL;
push(head,5);
push(head,9);
push(head,4);
push(head,6);
// disp(head);
pop(head);
// disp(head);
return 0;
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 堆栈粉碎 在我在代码中添加新变量以及一些操作后C++检测到
- 在此堆栈操作中我哪里出错了?
- RPN计算器使用头文件进行计算操作和堆栈;用于堆栈的矢量
- 当提供巨大的输入时,中止在堆栈操作程序中调用错误
- 根据堆栈操作 c++ 计算元素的最大数量
- 为什么这个函数将RAX推送到堆栈作为第一个操作
- 堆栈弹出操作是否可以安全地返回 C++11 中的值
- 使用链表进行堆栈弹出操作
- 生产者和使用者函数,用于在操作手册中测试C++并发的线程安全堆栈示例
- 使用2个堆栈在O(1)中执行extractMin操作
- 展开操作期间遇到无效或未对齐的堆栈
- C++STL堆栈弹出操作导致分段错误
- 阻塞/等待堆栈操作
- 不支持的操作.由JRC引擎处理的文档不能在c++堆栈中打开
- 当在有限递归循环中操作大型数组时,我应该在哪一点从堆栈切换到堆?