資料結構:實驗四棧和佇列的基本操作實現及其應用
阿新 • • 發佈:2019-01-25
一、實驗目的
1,熟練掌棧和佇列的結構特點,掌握棧和佇列的順序儲存和鏈式儲存結構和實現。
2,學會使用棧和佇列解決實際問題。
二、實驗內容
1,自己確定結點的具體資料型別和問題規模:
分別建立一個順序棧和鏈棧,實現棧的壓棧和出棧操作。
分別建立一個順序佇列和鏈佇列,實現佇列的入隊和出隊操作。
2,設計演算法並寫出程式碼,實現一個十將二進位制轉換成2進位制數。“
三.實驗報告
1.實驗程式碼如下:
#include<iostream>
using namespace std;
template < typename T >
struct Node
{
T data;
Node<T> *next;
};
template < typename T >
class LinkStack {
public:
LinkStack(T array[], int n)
{
top = NULL;
Node<T> *node = NULL;
for (int i = 0; i < n; i++) {
node = new Node<T>;
node->data = array[i];
node->next = top;
top = node;
}
}
~LinkStack()
{
Node<T> *deleteNode = NULL;
deleteNode = top;
top = top->next;
delete deleteNode;
}
void push(T x);
T pop();
void print();
T gettop() { if (top != NULL) return top->data; }
int Empty() { top == NULL ? return 1 : return 0; }
private:
Node <T> *top;
};
template < typename T >
void LinkStack<T>::push(T x)
{
Node<T> *s;
s = new Node<T>;
s->data = x;
s->next = top;
top = s;
}
template < typename T >
T LinkStack<T>::pop()
{
T x;
Node<T> *p;
if (top == NULL)throw"下溢";
x = top->data; p = top;
top = top->next;
delete p;
return x;
}
template <class T>
void LinkStack<T>::print()
{
Node<T> *node = top;
while (node->next != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << node->data << endl;
}
void main()
{
int arr[] = { 1,2,3,4,5 };
cout << "建立物件:1,2,3,4,5依次入棧 " << endl;
LinkStack<int> a(arr, 5);
cout << "遍歷棧內的元素:";
a.print();
cout << "出棧一個元素" << a.pop() << endl;
cout<<"結果如下:" ;
a.print();
cout << "現在棧頂元素為:" << a.gettop();
cout << "入棧元素6~10:" << endl;
for (int i = 6; i <= 10; i++)
{
a.push(i);
}
cout << "遍歷棧內的元素:";
a.print();
}
2.實驗結果
四.實驗總結
創立物件1,2,3,4,5依次入棧,遍歷結果5,4,3,2,1,出棧一個元素5,得遍歷結果4,3,2,1,入棧元素6,7,8,9,10,遍歷結果10,9,8,7,6,4,3,2,1.