1、完成一个Link类
class link
{
pubilc:
link();
link(const link&);
//接口:
bool insert(...);//头插法
bool drop(..);//
bool find(...);
~link();
protected:
Node* head;
};
2、在完成第一题基础上:
class stack:public link
{
//构造器:
bool push();
bool pop();
bool isfull();
bool isempty();
private:
int ilen;//记录栈的长度
};
创建一个 link 的文件 (没有后缀名)
class Node
{
public:
Node();
Node(int);
//声明友元类:link可以访问node节点
friend class Link;
protected:
int data;
Node* next;
};
class Link
{
public:
Link();
Link(const Link&);
bool insert(int);
bool dropHead(int&);
void copy(Node*);
private:
Node* head;
};
创建一个 link.cpp 的文件 .
#include<iostream>
using namespace std;
#include "link"
//实现类方法的定义
Node::Node():next(NULL)
{
}
Node::Node(int d):next(NULL),data(d)
{
}
//实现Link类的方法的定义
Link::Link():head(NULL)
{
}
Link::Link(const Link& l) //拷贝构造
{
this->head=NULL;
this->copy(l.head);
}
//复制
void Link::copy(Node* ploc)
{
if(ploc==NULL)
return;
// 3-2-1 1 2 3
copy(ploc->next);
this->insert(ploc->data);
}
//头插法
bool Link::insert(int d)
{
//1.插入节点:
Node* pnew=new Node(d); //有参构造
//2.修改指向域
if(NULL!=pnew)
{
pnew->next=this->head;
this->head=pnew;
cout<<"插入成功"<<d<<endl;
return true;
}
return false;
}
bool Link::dropHead(int &d)
{
Node* temp=this->head;
if(this->head!=NULL)
{
d=this->head->data;
this->head=this->head->next;
delete temp;
return true;
}
return false;
}
/*
int main()
{
Link l;
for(int i=1;i<5;i++)
l.insert(i);
Link l2(l);
cout<<"l2:"<<l2->data<<endl;
}
*/
创建一个 stack.cpp 的文件 .
#include<iostream>
using namespace std;
#include"link"
//私有继承:继承,新增
class Stack:private Link
{
public:
Stack();
Stack(const Stack&);
bool push(int);
bool pop(int&);
bool isEmpty();
int StackLength();
protected:
//新增
int ilen; //长度
//继承...
};
//构造器
Stack::Stack():Link(),ilen(0)
{
}
Stack::Stack(const Stack& s):ilen(s.ilen),Link(s)
{
//this->ilen=s.ilen;
}
//压栈
bool Stack::push(int d)
{
if(this->insert(d)==true)
{
this->ilen++;
return true;
}
return false;
}
bool Stack::isEmpty()
{
if(0==this->ilen)
return true;
return false;
}
bool Stack::pop(int& d)
{
if(this->isEmpty())
return false;
if(this->dropHead(d)==true)
{
this->ilen--;
return true;
}
return false;
}
int Stack::StackLength()
{
return this->ilen;
}
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
Stack s2(s);
//s2将s的内容复制给自己
//出栈s
int d;
while(s.pop(d))
{
cout<<d<<" ";
}
cout<<endl;
//出格s2
while(s2.pop(d))
{
cout<<d<<" ";
}
cout<<endl;
}