数据结构(C语言版)严蔚敏算法(第三章)C++实现

这里写自定义目录标题

栈和队列

这是书中第三章的例子,后面的后继续更新。

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

借鉴

借鉴.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值