棧在概念方面確實沒有提的必要了。看了數(shù)據(jù)結(jié)構(gòu)的這一部分,就將書中的一小段代碼實現(xiàn)了。這里用到了標(biāo)準(zhǔn)庫中的stack。下面就是根據(jù)輸入的十進制正數(shù)獲取二進制正數(shù)的程序(書上是八進制):
1 #include <stack>
2 #include <iostream>
3 using namespace std;
4 int _tmain(int argc, _TCHAR* argv[])
5 {
6 stack<int> binaryStack;
7 int decimalValue;
8 cout<<"please input decimal value:";
9 cin>>decimalValue;
10 while(decimalValue)
11 {
12 binaryStack.push(decimalValue%2);
13 decimalValue=decimalValue/2;
14
15 }
16 cout<<"\n"<<"the binary result is:";
17 while(!binaryStack.empty())
18 {
19 int result=(int)binaryStack.top();
20 binaryStack.pop();
21 cout<<result;
22 }
23 cout<<"\n";
24 return 0;
25 }
另外順便看了一下C#和JAVA,當(dāng)然也支持棧。但是這些東西在我平時使用的時候卻很少用到,或者在用到的時候去“重復(fù)發(fā)明輪子了”。作為一個經(jīng)典的數(shù)據(jù)類型,棧理應(yīng)是被絕大多數(shù)語言支持的(不知道PB怎樣)。所以在這里要樹立一下“重用輪子”的意識:
C#的十進制轉(zhuǎn)二進制實現(xiàn):
1 class Class1
2 {
3 /// <summary>
4 /// 應(yīng)用程序的主入口點。
5 /// </summary>
6 [STAThread]
7 static void Main(string[] args)
8 {
9 //
10 // TODO: 在此處添加代碼以啟動應(yīng)用程序
11 //
12 Stack binaryStack=new Stack();
13 Console.WriteLine("Please input decimal value:");
14 String sDecimal=Console.ReadLine();
15 int decimalValue=Int32.Parse(sDecimal);
16 while(decimalValue!=0)
17 {
18 binaryStack.Push(decimalValue%2);
19 decimalValue=decimalValue/2;
20 }
21 Console.WriteLine("The binary result is:");
22 while(binaryStack.Count!=0)
23 {
24 Console.Write(binaryStack.Pop());
25 }
26 Console.WriteLine();
27 }
28 }
JAVA的十進制轉(zhuǎn)二進制實現(xiàn):
1 import java.io.BufferedReader;
2 import java.io.InputStreamReader;
3 import java.util.Stack;
4 public class hello1 {
5 public static void main(String args[])
6 {
7 try {
8 Stack<Integer> binaryStack=new Stack<Integer>();
9 int decimalValue;
10 System.out.println("please input decimal value:");
11 BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
12 decimalValue=Integer.parseInt(bufferedReader.readLine());
13 while(decimalValue!=0)
14 {
15 binaryStack.push(decimalValue%2);
16 decimalValue=decimalValue/2;
17 }
18 System.out.println("the binary result is:");
19 while(!binaryStack.empty())
20 {
21 System.out.print(binaryStack.pop());
22
23 }
24 } catch (Exception e) {
25 // TODO Auto-generated catch block
26 e.printStackTrace();
27 }
28
29
30 }
31 }
通過比較,會發(fā)現(xiàn)C#不大有“棧”的感覺,JAVA和C++更貼近于《數(shù)據(jù)結(jié)構(gòu)》中對于數(shù)據(jù)類型“棧”的操作的定義。另外支持模板或者范型的特點讓人用起來總會感覺十分舒服。在這里提醒自己:以后這三種語言有“棧”可用了!
posted on 2007-06-11 22:11
littlegai 閱讀(195)
評論(0) 編輯 收藏 引用 所屬分類:
我的讀書筆記