上午再一次深入複習了棧的算法實現,寫了一個簡單的十進制轉二進制函數作爲練習(以後有時間的時候再將其中關鍵部分用圖文描述出來,加深印象的同時也希望能夠幫助初學者更好的理解這部分的知識),代碼如下:
// ConsoleApplication2.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
//==================以下是棧的數據結構和方法=================
typedef struct Stack{
int data;
struct Stack* Next;
}Stack;//棧結構定義
void initStack(Stack* &S)//初始化棧,帶頭結點的棧
{
S = (Stack*)malloc(sizeof(Stack));
S->Next = NULL;
}
int StackEmpty(Stack* S)//判斷棧是否爲空
{
if (S->Next == NULL)
return 1;
else
return 0;
}
void StackPush(Stack* S, int x)//入棧
{
Stack* p = (Stack*)malloc(sizeof(Stack));//申請一個結點
p->Next = NULL;
p->data = x;
p->Next = S->Next;//令新結點的Next指針指向首結點
S->Next = p;//將頭結點的Next指針指向新結點
}
int StackPop(Stack* S, int &x)//出棧
{
if (S->Next == NULL)//判斷棧是否爲空
return 0;
else
{
Stack* p = S->Next;//令p指向棧頂結點
S->Next = p->Next;//令頭結點的Next指針指向棧頂結點的下一個結點,之前的棧頂結點的下一個結點變爲新的棧頂結點
x = p->data;//將之前棧頂結點的值賦給x
free(p);//釋放之前的棧頂結點
return 1;
}
}
//===========以下是運用棧進行10進制轉2進制的函數====================
void Transfer(int x)
//只能對大於0的十進制進行二進制轉換
{
int temp = x;
Stack* S;
initStack(S);
while (x != 0)//判斷x是否爲零
{
StackPush(S, x % 2);//將x除2的餘數入棧
x = int(x / 2);//x除2,並向下取整
}
cout << temp << " transfer to binary is:\n";
while (!StackEmpty(S))
{
StackPop(S, x);//出棧並打印
cout << x << ' ';
}
cout << '\n';
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 1; i < 11;i++)
Transfer(i);
cout << "\ndone!\n";
return 0;
}
/*=======================在VS2013中的輸出結果======================
1 transfer to binary is:
1
2 transfer to binary is:
1 0
3 transfer to binary is:
1 1
4 transfer to binary is:
1 0 0
5 transfer to binary is:
1 0 1
6 transfer to binary is:
1 1 0
7 transfer to binary is:
1 1 1
8 transfer to binary is:
1 0 0 0
9 transfer to binary is:
1 0 0 1
10 transfer to binary is:
1 0 1 0
done!
請按任意鍵繼續. . .
*/