您的位置:首页 > 其它

3)链栈和链队列

2015-12-05 18:26 246 查看
链栈:

#include<iostream>
using namespace std;
struct node{
int data;
node *next;
};
enum error{underflow,overflow,success,fail};
class stack{
public:
stack();//初始化
~stack();//定义析构函数,以在需要时自动释放链栈空间
bool empty() const;//判断为空
bool full() const;//判断为满
int get_top(int &x)const;//取栈顶元素
int push(const int x);//入栈
int pop();//出栈
private:
int count;//栈中数据的个数
int data;//栈中数据
node *top;
};
/*初始化:栈顶指针置为空,计数变量设置为0*/
stack::stack(){
count=0;
top=NULL;
}

/*
*判断栈是否为空:count=0||top=NULL
*/
bool stack::empty()const{
return count==0;//return top==NULL;
}

/*
*取栈顶元素的实现,若栈不为空,返回栈顶元素的值,否则返回出错信息
*/
int stack::get_top(int &x)const{
if(empty())return underflow;
x=top->data;
return success;
}

/*
*入栈
*/
int stack::push(const int x){
node *s=new node;
s->data=x;
s->next=top;
top=s;
count++;
return success;
}

/*
出栈
*/
int stack::pop(){
if(empty())return underflow;
node *u=new node;
u=top;
top=u->next;
delete u;
count--;
return success;
}

stack::~stack(){
while(!empty())pop();
}

int xchg(int n,stack s){
cout<<"十进制:["<<n<<"]->8进制:";
int mod,x;
while(n!=0){
mod = n % 8;
s.push(mod);
n/=8;
}
while(s.empty()!=true){
s.get_top(x);
cout<<x;
s.pop();
}
cout<<endl;
return 0;
}
int main()
{
stack s;
xchg(100,s);
return 0;
}


链队列:

#include<iostream>
#include<iomanip>
using namespace std;

enum error{underflow,overflow,success};

struct node{
int data;
node *next;
};

class queue{
public:
queue();
~queue();//定义析构函数,以在需要时自动释放链队列空间
bool empty() const;//判断为空
bool full() const;//判断为满
int get_front(int &x )const;//取队头元素
int append(const int x);//入队
int serve();//出队
private:
int count;
node *front,*rear;
};

queue::queue(){//初始化队列
front =new node;
rear =new node;
//node *rear = new node;
count=0;
rear = front;
front->next=NULL;
rear->next=NULL;
}

bool queue::empty()const{//判断为空
if(count==0)return true;
else return false;
//    return count==0;
}

int queue::get_front(int &x)const{//取队头元素
if(empty())return underflow;
else{
x=front->next->data;
return success;
}
}

int queue::append(const int x){//入队
node *s= new node;
s->data=x;
s->next=NULL;
rear->next=s;
rear=s;
count++;
return success;
}

int queue::serve(){//出队
node *u =new node;
if(empty())return underflow;
else{
u=front->next;
front->next=u->next;
delete u;
count--;
}
if(front->next==NULL)rear=front;//如果删除的是最后一个结点,尾指针rear指向了一个已经删除的节点
return success;
}

queue::~queue(){
while(!empty())  serve();
delete front;//最后释放头结点
}

int main(){
queue q;
int n;
cout<<"please input 杨辉三角要打印的行数:";
cin>>n;
int s1,s2;
for(int i=1;i<n;i++)cout<<"  ";
cout<<1<<endl;//输出第一行上的1
q.append(1);//所输出1入队
for(int i=2;i<=n;i++){//逐行计算并输出2~N行上的数据
s1=0;//存放前一个入队数
for(int k=1;k<=n-i;k++ )cout<<"  ";
for(int j=1;j<=i-1;j++){//先计算并输出n-1个数
q.get_front(s2);//取队头元素并出队
q.serve();
cout<<s1+s2<<setw(4);
q.append(s1+s2);//所输出的当行中的元素入队
s1=s2;
}
cout<<1<<endl;//输出当行中的子最后一个元素1并换行
q.append(1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: