乙個c c 函式呼叫棧的實現

2021-05-08 10:55:47 字數 1884 閱讀 6222

函式呼叫棧的實現。可用於實現簡單的指令碼直譯器。

宣告:#pragma once

const int buffersize = 1024;

const int growfactor = 2;

// this stack is used as call stack.

class tstack  // push an int

void pushlong(long l)  // push a long

void pushfloat(double f)  // push  a double

void pushpointer(void* p)

// int 

int popint()  // pop an int

long poplong()  // pop an int    

double* popfloat()  // pop a double

void* poppointer()

void clear()   

實現:#include "stdafx.h"

#include "tstack.h"

#include "new.h"

void tstack::push( void* d, size_t bytecount )

// if memory is not enough

// if run under multithread envionment,

// a lock or critical section should be added

if (pos + bytecount > size)

size_t oldsize = size;

size *= growfactor;   

char *newbuffer = new char[size];

memcpy(newbuffer, buffer, oldsize);

delete buffer;

buffer = newbuffer;   

memcpy(buffer+pos, d, bytecount);

pos += bytecount;

void* tstack::pop( size_t bytecount )

// need synchronization for multithread environment

pos -= bytecount;

return &buffer[pos];

tstack::tstack( size_t _size , size_t _pos )

:size(_size),

pos(_pos),

buffer(new char[size])

tstack::tstack( const tstack &o )

:size(o.size),

pos(o.pos)

buffer = new char[size];

if (buffer != null)

memcpy(buffer, o.buffer, size);

tstack& tstack::operator=( const tstack& o )

if (this == &o)

return *this;     

this->size = o.size;

this->pos = o.pos;

if (buffer != null)

delete buffer;

buffer = new char[this->size]; 

if (buffer != null)

memcpy(buffer, o.buffer, this->size);

return *this;

只用乙個函式實現翻轉棧

給你乙個棧,請翻轉棧裡的元素 1,只能在函式裡定義常數級別的變數.2,不用考慮複雜度,指數級,階乘級複雜度都可以接受 3,除了基礎的主函式以及輸入外,關於演算法邏輯的函式只能用下面介面 函式介面為 void reverse stack int st int a st.top st.pop if st...

C C 之用兩個棧實現乙個佇列的功能

問題 有兩個棧s1和s2,實現佇列的push和pop功能。一般思路 始終維護s1作為儲存空間,並以s2作為臨時緩衝區。s1實現入隊操作,s2實現出隊操作。1,入隊時,將元素壓入s1。2,出隊時,將s1的元素逐個 倒入 彈出並壓入 s2,將s2的頂元素作為出隊元素,之後再將s2剩下的元素逐個 倒回 s...

用乙個棧實現另外乙個棧的排序

題目 乙個棧中的型別為整形,現在想將該棧從頂到底按從小到大的順序排序,只允許申請乙個棧 除此之外,可以申請新的變數,但是不能申請額外的資料結構,如何完成排序。思路 設計乙個cur變數,存放stack棧彈出的當前元素,和輔助棧help的棧頂元素進行比較,若大於輔助棧棧頂元素,則將輔助棧中元素一一彈出,...