// stack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
class node
{
friend class list;
private:
node* next;
int data;
public:
node(node* nextp=NULL)
{
next=nextp;
}
node(const int& item,node* nextp=NULL)
{
data=item;
next=nextp;
}
};
class list
{
private:
node* head;
int size;
void clearlist(void);
node* index(int pos)const;
public:
list(void);
~list(void);
int listsize(void)const;
int listempty(void)const;
void insert(const int& item,int pos);
int del(int pos);
int getdata(int pos)const;
};
list::list()
{
head=new node(NULL);
size=0;
}
list::~list(void)
{
clearlist();
delete head;
}
void list::clearlist(void)
{
node* start;
node* temp;
start=head->next;
while(start!=NULL)
{
temp=start;
start=start->next;
delete temp;
}
size=0;
}
node* list::index(int pos) const
{
if(pos<-1||pos>size)
{
cout<<"pos isnot in range"<<endl;
exit(0);
}
if(pos==-1)
return head;
node* p=head->next;
int i=0;
while(p!=NULL&&i<pos)
{
p=p->next;
i++;
}
return p;
}
int list::listsize(void)const
{
return size;
}
int list::listempty(void)const
{
if(size<=0)return 1;
else return 0;
}
void list::insert(const int& item,int pos)
{
node* p=index(pos-1);
node* newnode=new node(item,p->next);
p->next=newnode;
size++;
}
int list::del(int pos)
{
if(size==0)
{
cout<<"there is no element left to delete"<<endl;
exit(0);
}
node* p=index(pos-1);
node* q;
q=p->next;
p->next=q->next;
int da=q->data;
delete q;
size--;
return da;
}
int list::getdata(int pos)const
{
node* p=index(pos);
return p->data;
}
class stacklist:private list
{
public:
stacklist(void):list()
{}
~stacklist(void)
{}
int stacksize(void)const
{
return listsize();
}
void push(const int& item)
{
insert(item,0);
}
int pop(void)
{
return del(0);
}
int gettop(void)
{
return getdata(0);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
stacklist mystack;
int i;
cout<<"the initial number of elements is "<<mystack.stacksize()<<endl;
for(i=0;i<5;i++)
mystack.push(i);
cout<<"after pushing,the number of elements is "<<mystack.stacksize()<<endl;
for(i=0;i<5;i++)
cout<<mystack.pop()<<" ";
cout<<endl;
cout<<"at last,the number of elements is "<<mystack.stacksize()<<endl;
return 0;
}