在熟悉使用棧的基礎(chǔ)上可以用其實現(xiàn)很多有趣算法,比如給定一個十進制數(shù)铡原,轉(zhuǎn)換為二進制數(shù)。
#include <iostream>
using namespace std;
typedef int elemType;
typedef struct stackNode {
elemType data;
struct stackNode *next;
} stackNode, *S;
bool initStack(S &s) {
s = NULL;
return true;
}
bool push(S &s, elemType e) {
S p;
p = new stackNode;
if (!p) return false;
p->data = e;
p->next = s;
s = p;
return true;
}
bool pop(S &s, elemType &e) {
if (!s) return false;
S p;
p = s;
s = s->next;
e = p->data;
delete p;
return false;
}
bool getTop(S s, elemType &e) {
if (!s) return false;
e = s->data;
return true;
}
bool isEmpty(S s) {
if (!s) return true;
else return false;
}
void binaryConversion(int n) {
S s;
initStack(s);
while (n) {
push(s, n % 2);
n = n / 2;
}
int e;
while (!isEmpty(s)) {
pop(s, e);
cout << e << "\t";
}
}
int main() {
binaryConversion(30);
return 0;
}
Output:
1 1 1 1 0