栈和队列
这是书中第三章的例子,后面的后继续更新。
3.1 栈
源文件
#include "s1.h"
int main()
{
int n = 5;
int arr[] = { 1,2,3,4,5 };
Sqstack s1;
s1.InitStack(arr, n);
cout << s1 << endl;
return 0;
}
头文件
#pragma once
#include<iostream>
using namespace std;
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
class Sqstack {
private:
int* base;
int* top;
int stacksize;
int Stack_len;
public:
Sqstack() {
this->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));
this->top = this->base;
this->stacksize = STACK_INIT_SIZE;
int Stack_len = this->top - this->base;
};
Sqstack(int values[], int n)
{
this->InitStack(values, n);
}
//~Sqstack();
void InitStack(int value[], int n) {
this->Stack_len = n;
this->stacksize = n * 2;
this->base = new int[this->stacksize];
for (int i = 0; i < Stack_len; ++i) {
base[i] = value[i];
}
this->top = this->base + this->StackLength();
};
void DestroyStack() {
delete this->base;
delete this->top;
};
void ClearStack() {
this->top = this->base;
};
bool StackEmpty() {
return this->base == this->top;
};
int StackLength() {
return this->Stack_len;
};
int GetTop() {
if (!StackEmpty())
{
int e = *(this->top - 1);
int t = base[Stack_len - 1];
/*cout<<this->Stack_len<<endl;*/
/*cout << e<<endl;*/
/*cout << t << endl;*/
return e;
}
};
void Push(int e) {
if (this->Stack_len >= this->stacksize) {
this->base = (int*)realloc(this->base, (this->stacksize + STACKINCREMENT) * sizeof(int));
this->top = this->base + this->Stack_len;
this->stacksize += STACKINCREMENT;
}
*(this->top++) = e;
++this->Stack_len;
};
int Pop() {
if (this->base != this->top) {
int e = *(this->top);
--(this->top);
Stack_len--;
}
else {
return -1;
}
return 0;
};
friend ostream& operator<<(ostream& out, Sqstack& List) {
for (int i = 0; i < List.StackLength(); i++) {
if (List.StackLength() == 1) {
out << List.GetTop();
}
out << List.GetTop() << ",";
List.top--;
}
return out;
};
};
3.2.1数制转换
void conversion(Sqstack &s) {
int n,j;
cout << "请输入要转换的十进制数:" << endl;
cin >> n;
cout << "请输入要转换几进制数:" << endl;
cin >> j;
while (n) {
s.Push(n % 8);
n = n / j;
}
}
int main()
{
int n = 5;
int arr[] = { 1,2,3,4,5 };
Sqstack s1;
s1.InitStack(arr, n);
s1.ClearStack();
cout << s1 << endl;
conversion(s1);
cout << s1 << endl;
return 0;
}
借鉴
借鉴.