#include
using namespace std;
struct Node
{
struct Node* next;
int elem;
};
Node* push(Node* head, int elem2)
{
Node* temp=(Node*)malloc(sizeof(Node));
if (temp != NULL)//判断内存空间是否申请成功
{
temp->next = head;
temp->elem = elem2;
head = temp;
}
return head;
}
void display(Node* head)
{
Node* temp2 = head;
Node* temp3 = NULL;
if (temp2)
{
cout << endl << "链栈:";
while (temp2)
{
cout << temp2->elem << " ";
temp3 = temp2->next;
temp2 = temp3;
}
}
else
{
cout << endl << "空栈,没有可输出的链栈元素";
}
}
Node* pop(Node* head)
{
Node* temp4= NULL;
if (head)
{
temp4= head;
head = temp4->next;
cout << "弹栈元素:" << temp4->elem;
free(temp4);
}
else
{
cout <<endl<<"空栈,没有可弹出的元素";
}
return head;
};
int main()
{
Node* head = NULL;
int n;
cout<<"请输入压入栈中的数据元素个数:";
cin>>n;
int elem2;
int i;
for(i=1;i<= n; i++)
{
cout<<"请输入压入栈中的第"<<i<<"个元素:";
cin>>elem2;
push(head,elem2);
}
display(head);
int nn;
cout<<endl<< "请输入要弹出栈的数据元素个数:";
cin>>nn;
int ii;
for(ii=0;ii<nn;ii++)
{
pop(head);
}
display(head);
return 0;
}
Node* push(Node* head, int elem2)
push(head,elem2);,你的push返回head指针需要用main中head接收更新,不然就只是NULL。