构造堆栈:Private List Can Be Converted To Stacklist

本文介绍了一个基于链表实现的栈类的设计与应用。通过定义节点类和列表类,实现了栈的基本操作如压栈(push)、弹栈(pop)及获取栈顶元素(gettop),并展示了栈的操作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值