//
// main.cpp
// stack
//
// Created by EriceRacy on 16-11-6.
// Copyright (c) 2016年 EriceRacy. All rights reserved.
//
#include <iostream>
#include<stdlib.h>
using namespace std;
struct stack{
int *st;
int stackSize;
int top;
};
void init_stack(stack *s){
s->stackSize=10;
s->st=new int[s->stackSize];
s->top=-1;//algorithms里的数组第一元素位置从1开始的,它那里top=0,写的时候top就得=0.
}
int STACK_EMPTY(stack s){
return ((s.top==0) ? 1 : 0);
}
void push_stack(stack *s, int a){//这里是不是也可以用引用呢?stack
if (s->top==s->stackSize) {
cout<<"Overflow!";
}
else{
s->top++;
s->st[s->top]=a;//如果这里top是0,那么下面自增后,top指的就不再是当前最尾的元素了。
}
}
int pop_stack(stack *s){
if (STACK_EMPTY(*s)) {
cout<<"Underflow!";
return 1;
}
else{
s->top--;
return (s->st[s->top+1]);
}
}
int top_stack(stack s){
return (s.st[s.top]);
}
int main(int argc, const char * argv[]) {
int i=0,m;
stack s;
init_stack(&s);
for (i=0; i<10; i++) {
cin>>m;
push_stack(&s, m);
}
for (i=0; i<5; i++) {
//pop_stack(&s);
cout<<top_stack(s)<<" ";
pop_stack(&s);
}
cout<<s.st[0];
return 0;
}
11.6
简单的数组实现的栈
数组用了结构体定义其及其属性(top)
//
// main.cpp
// queue
//
// Created by EriceRacy on 16-11-6.
// Copyright (c) 2016年 EriceRacy. All rights reserved.
//
#include <iostream>
#include<stdlib.h>
using namespace std;
struct queue{
int *qu;
int queueSize;
int head;
int tail;
};
void init_queue(queue *s){
s->queueSize=10;
s->qu=new int[s->queueSize];
s->head=s->tail=-1;//algorithms里的数组第一元素位置从1开始的,它那里top=0,写的时候top就得=0.
}
int QUEUE_EMPTY(queue s){
return ((s.head==s.tail) ? 1 : 0);
}
void enqueue(queue *s, int a){//这里是不是也可以用引用呢?stack
s->qu[s->tail]=a;
if (s->tail+1==s->head) {
cout<<"Overflow!";
}
if (s->tail==s->queueSize) {
s->tail=0;
}
else{
s->tail++;
}
}
int dequeue(queue *s){
int x;
x=s->qu[s->head];
if (s->head==s->queueSize) {
s->head=0;
}
else{
s->head++;
}
return x;
}
//int top_stack(stack s){
// return (s.st[s.top]);
//}
int main(int argc, const char * argv[]) {
int i=0,m;
queue s;
init_queue(&s);
cout<<"Creat a new queue, input your ten numbers. "<<endl;
for (i=0; i<10; i++) {
cin>>m;
enqueue(&s, m);
}
cout<<"Now delete four nembers, they are: "<<endl;
for (i=0; i<5; i++) {
cout<<dequeue(&s)<<" ";
}
cout<<endl;
//cout<<s.qu[0];
//cout<<s.head;
cout<<"Now the queue is: "<<endl;
for (i=0; i<(s.queueSize-s.head-1); i++) {
cout<<s.qu[s.head+i]<<" ";
}
cout<<endl;
return 0;
}
11.6
队列的简单数组实现。
据算法导论上的思想而码,实现过程中参考了@chenxun_2010的文章,在此感谢!
注释有时间会多加一些上去。