c/c++模拟推栈

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 ;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值