1. 用链表模拟堆栈
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Snode)
struct Snode
{
int data;
struct Snode *next;
};
struct Snode *top=NULL;
void Print_list()
{struct Snode *p;
p=top;
if(p==NULL)
{printf("the top is empty");}
else
{while(p!=NULL)
{
printf("%d /n",p->data);
p=p->next;
} //{ }不可丢!!!!
}
}
void push(int value)
{ struct Snode *newp;
newp=(struct Snode *)malloc(LEN);
newp->data=value;
newp->next=top;
top=newp;
}
int pop()
{struct Snode *temp;
if(top==NULL)
printf("the top is empty/n");
else
{temp=top;
top=top->next;
free(temp);
}
}
main()
{ int value;
while(1)
{ printf("please input the number");
scanf("%d",&value);
if(value==-1)
break;
else
push(value);
}
printf("the stack now is/n");
Print_list();
getch();
}
2. 用数组模拟堆栈
// simulateStackusingArray.cpp : 定义控制台应用程序的入口点。
//
#include " stdafx.h "
#include < iostream >
using namespace std;
const int size = 100 ;
template < typename T >
class IStack
...{
public :
IStack();
T pop ();
int push (T);
int display();
private :
T IArray [size];
int count;
};
template < typename T >
IStack < T > ::IStack()
...{
for ( int i = 0 ; i < size; i ++ )
...{
IArray[i] = 0 ;
}
count = 0 ;
}
template < typename T >
T IStack < T > ::pop()
...{
T temp = IArray[count - 1 ];
count -- ;
return temp;
}
template < typename T >
int IStack < T > ::push(T rhs)
...{
IArray [count ++ ] = rhs;
return 0 ;
}
template < typename T >
int IStack < T > ::display()
...{
for ( int i = 0 ; i < count; i ++ )
...{
cout << IArray[i] << " " ;
}
return 0 ;
}
// template <typename T>
// int IStack<T>::getcount()
// {
// return count;
// }
int main()
...{
IStack < int > istack;
istack.push( 2 );
istack.push( 4 );
istack.push( 3 );
istack.pop();
istack.display();
return 0 ;
}