【发布时间】:2014-12-29 09:54:03
【问题描述】:
列表中的元素是 6495,即前 5 个被推送,然后是 9 个,依此类推。现在我想弹出 5(我知道前 6 个应该根据 FILO),即以相反的顺序。在我第一次和第二次进行弹出操作时,弹出的元素都是 5。 Temp 是一个局部变量,所以即使我在 pop 函数中释放它,如果我要在 main 中显示元素,它也不会在 main 中释放?这是真的吗?但无论如何我在 pop 操作本身中做了我的 cout 但是它仍然不工作?如果我使用 display 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;
}
【问题讨论】:
-
为什么在 C++ 代码中使用
free?您为什么不使用其中一种标准模板来执行此操作? -
@EdHeal 它不会引起任何问题。(也不是警告)。那我应该用什么?
-
@Rooney10 至少你没有分配任何东西,那么
free()'d 应该在那里? -
@Rooney10
new/delete用于 C++,malloc/free用于 C -
@πάνταῥεῖ 没错,但我应该用什么来代替免费。问题出在空闲部分,temp 是一个局部变量,我们也没有为它分配任何内存,但是使用 temp 作为全局变量,我得到的输出也不正确,所以问题一定出在空闲部分