// CTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string.h> #include <stdio.h> using namespace std; typedef int ElemType; struct Stack{ ElemType data; Stack *next; }; void InitStack(Stack* &HS){ HS = NULL; } void Push(Stack* &s,const ElemType &item){//元素item进栈,即插入到栈顶 //为插入元素获取动态节点 Stack * newptr = new Stack; //给新分配的节点赋值 newptr->data=item; //向栈顶插入新结点 newptr->next=s; s=newptr; } ElemType Pop(Stack* &s){//删除栈顶元素,并返回 if(s==NULL){ cerr<<"Linked stack is empty!"<<endl; exit(1); } Stack *p= s;//暂存栈顶结点指针 s = s->next;//使栈顶指针指向下一个节点 ElemType temp = p->data;//暂存原栈顶元素 delete p; //回收原栈顶结点 return temp; } ElemType Peek(Stack* &s){//读取栈顶的元素 if(s==NULL){ cerr<<"Linked stack is empty!"<<endl; exit(1); } return s->data; } bool EmptyStack(Stack* &s){//清空栈 return s==NULL; } void ClearStack(Stack* &s){ Stack *cp,*np; cp = s; while(cp!=NULL){ np = cp->next; delete cp; cp = np; } s = NULL; } int _tmain(int argc, _TCHAR* argv[]) { Stack *s; InitStack(s);//初始化栈 int x;//从键盘上输入x cin >>x; while(x!=-1){ Push(s,x);//向栈中加入数据 cin>>x; } while(!EmptyStack(s)){//如果栈不为空 cout<<Pop(s)<<‘ ‘; } cout<<endl; ClearStack(s); system("pause"); return 0; }
输入数据 9 8 1 2 3 5 6 -1 9 3 4
输出数据6 5 3 2 1 8 9
时间: 2024-10-08 12:57:02