在熟悉使用栈的基础上可以用其实现很多有趣算法,比如给定一个十进制数,转换为二进制数。
#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