阿摩線上測驗 登入

申論題資訊

試卷:94年 - 94 地方政府特種考試_三等_資訊處理:程式語言#38549
科目:程式語言
年份:94年
排序:0

題組內容

四、

申論題內容

(1) 選用 ADA、C++、JAVA 中之任一程式語言,以抽象資料結構(Abstract data type) 或物件(Object)技術,設計堆疊(Stack)與其相關函數,堆疊中每一元素(Element) 包含有一個 16 位元組(Byte)的文字。

詳解 (共 1 筆)

詳解 提供者:s1121ks011 s1121ks011
以下是使用Ada、C++和Java分別實現堆疊(Stack)及相關函數,其中每個元素包含一個16位元組(Byte)的文字:
### Ada
```ada
-- Stack.ads
generic
   type Element is private;
package Stack is
   type Stack is limited private;
   procedure Push(Item : Element; S : in out Stack);
   procedure Pop(S : in out Stack);
   function Top(S : Stack) return Element;
   function IsEmpty(S : Stack) return Boolean;
private
   type Node;
   type NodePtr is access Node;
   type Node is
      record
         Data : Element;
         Next : NodePtr;
      end record;
   type Stack is
      record
         TopNode : NodePtr := null;
      end record;
end Stack;
-- Stack.adb
package body Stack is
   procedure Push(Item : Element; S : in out Stack) is
      New_Node : NodePtr := new Node'(Data => Item, Next => S.TopNode);
   begin
      S.TopNode := New_Node;
   end Push;
   
   procedure Pop(S : in out Stack) is
      Temp : NodePtr := S.TopNode;
   begin
      if Temp /= null then
         S.TopNode := Temp.Next;
         delete Temp;
      end if;
   end Pop;
   
   function Top(S : Stack) return Element is
   begin
      if S.TopNode /= null then
         return S.TopNode.Data;
      else
         raise Program_Error;
      end if;
   end Top;
   
   function IsEmpty(S : Stack) return Boolean is
   begin
      return S.TopNode = null;
   end IsEmpty;
end Stack;
```
### C++
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
    stack<string> myStack;
    // Push elements onto the stack
    myStack.push("Element 1");
    myStack.push("Element 2");
    myStack.push("Element 3");
    // Pop elements from the stack and print them
    while (!myStack.empty()) {
        cout << "Top: " << myStack.top() << endl;
        myStack.pop();
    }
    return 0;
}
```
### Java
```java
import java.util.Stack;
public class Main {
    public static void main(String[] args) {
        Stack<String> myStack = new Stack<>();
        // Push elements onto the stack
        myStack.push("Element 1");
        myStack.push("Element 2");
        myStack.push("Element 3");
        // Pop elements from the stack and print them
        while (!myStack.empty()) {
            System.out.println("Top: " + myStack.peek());
            myStack.pop();
        }
    }
}
```
這些程式碼示例實現了堆疊及相關函數,並在堆疊中存儲16位元組(Byte)的文字元素。