The Fourth Dimension Space

枯叶北风寒,忽然年以残,念往昔,语默心酸。二十光阴无一物,韶光贱,寐难安; 不畏形影单,道途阻且慢,哪曲折,如渡飞湍。斩浪劈波酬壮志,同把酒,共言欢! -如梦令

动态链表式堆栈 by abilitytao

//template_by_abilitytao_ACM
//many thanks to Mr Zhang Hong and Yu Ligong

#include 
<algorithm>
#include
<cstdio>
#include
<cmath>
#include
<cstdlib>
#include
<iostream>
#include
<cstdio>
using namespace std;
struct node {
    
int data;
    node 
*next;
}
;

class mystack 
{
private:
    node
* ptop;//定义栈顶指针
    int lenth;//定义堆栈的动态容量
public:
    mystack();
//重载默认构造函数
    int push(int num);//压栈操作
    int pop();//退栈操作
    int top();//返回栈顶元素
    int size();//返回堆栈的实际容量
    bool empty();
    
bool full();
}
;

mystack::mystack()
{

    ptop
=NULL;
    lenth
=0;
}



int mystack::push(int num)//操作成功,返回1;
{

    node 
*p=new node;
    p
->data=num;
    p
->next=ptop;
    ptop
=p;//由于链表式堆栈没有容量上线,故返回值为1;
    lenth++;
    
return 1;
    
return 0;
}


int mystack::pop()//堆栈为空返回0,操作成功返回所需要的整数;
{
    
if(ptop==NULL)
        
return 0;
    
int result;
    result
=ptop->data;
    node 
*p=ptop;
    ptop
=p->next;
    delete p;
    lenth
--;
    
return result;
}


int mystack::top()
{
    
if(ptop==NULL)
        
return 0;
    
return ptop->data;
}



int mystack::size()
{
    
return lenth;
}


bool mystack::empty()
{

    
if (ptop==NULL)
        
return true;
    
else
        
return false;
}


bool mystack::full()
{

    
return false;//仅仅为了提高模板的健壮性
}







//////////////////////////////////////////////////////////////////////////test data////////////////////////////////////////////////////////////////////////////
int main ()
{

    mystack test;
    test.push(
1);
    test.push(
2);
    test.push(
3);
    test.push(
4);
    test.push(
5);
    test.push(
6);
    test.push(
7);
    
int a=test.size();
    a
=test.top();
    a
=test.pop();
    a
=test.top();
    a
=test.pop();
    a
=test.top();
    a
=test.pop();
    a
=test.top();
    a
=test.pop();
    a
=test.pop();
    a
=test.pop();
    a
=test.top();
    a
=test.pop();
    a
=test.pop();
    a
=test.top();
    a
=test.empty();
}

posted on 2009-03-02 21:48 abilitytao 阅读(1076) 评论(3)  编辑 收藏 引用

评论

# re: 动态链表式堆栈 by abilitytao 2009-03-14 22:47 KingsamChen

额,似乎这个不算模板?
template<typename T>?  回复  更多评论   

# re: 动态链表式堆栈 by abilitytao 2009-03-14 22:49 KingsamChen

ps:如果压完栈,但是没有出栈就跳出,是不是Memory Leaks了?
pps:这个Comments的验证码有点BUG……  回复  更多评论   

# re: 动态链表式堆栈 by abilitytao[未登录] 2009-03-15 17:22 abilitytao

我说的不是 template<class T>的那种 这个是为了参加ACM专门写的 我感觉还应该加个clear函数 恩 下次要改进一下  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理