HFUT資料結構作業感悟與分析-----C++運用佇列解決楊輝三角
阿新 • • 發佈:2018-12-22
//程式碼沒有很詳細的解釋,如果不明白,請自己根據程式碼一行一行分析
//分析三到四層,即可明白其中的原理
//再有問題的話,請在下面留言
#include<iostream>
using namespace std;
//我自己寫的Queue,是使用鏈佇列實現的,相關知識可以在課本上查到
template<class T>
class Queue{
public:
class Node{//內部類,用來表示每個節點
public:
T value;
Node* next = NULL;
};
int length = 0;
Node* head = NULL;//佇列不同於棧,需要一個頭指標,用來訪問隊首
Node* tail = NULL;//一個尾指標用來在隊尾插入元素
Node* p = NULL;//一箇中間指標,用來過渡
void push(T val){//入隊操作
p = new Node;
p->value = val;
if(head == NULL){
head = p;
}else{
tail->next = p;
}
tail = p;
length++;
}
int size(){//隊伍的大小
return length;
}
T pop(){//和stl標準庫的pop()函式不一樣,不僅可以刪除頭元素,還可以將頭元素的值返回
T value = head->value;
p = head;
head = head->next;
delete p;
length--;
return value;
}
T front(){//返回隊伍的隊首元素
return head->value;
}
bool empty(){//判斷隊伍是否為空
return length == 0;
}
void show(){//我自己加入的一個從隊首到隊尾的一個輸出展示函式
p = head;
while(p != NULL){
cout << p->value << " ";
p = p->next;
}
cout << endl;
}
}; int main(){
int n;
cin >> n;//n為楊輝三角的層數
Queue<int> queue;
for(int i = 1; i <= n; i++){//n層,所以迴圈n次
for(int j = 0; j < i - 2; j++){//這個請讀者自行體會,大概自己寫個三四層之後,就能夠明白其中的原理了
queue.push(queue.pop() + queue.front());//這句語句非常簡練,請讀者自行體會,我認為比課本上的更加簡潔一些
}
queue.push(1);//這是很關鍵的一步
queue.show();//運算結束,展示每一行
}
return 0;
}
//分析三到四層,即可明白其中的原理
//再有問題的話,請在下面留言
#include<iostream>
using namespace std;
//我自己寫的Queue,是使用鏈佇列實現的,相關知識可以在課本上查到
template<class T>
class Queue{
public:
class Node{//內部類,用來表示每個節點
public:
T value;
Node* next = NULL;
};
int length = 0;
Node* head = NULL;//佇列不同於棧,需要一個頭指標,用來訪問隊首
Node* tail = NULL;//一個尾指標用來在隊尾插入元素
Node* p = NULL;//一箇中間指標,用來過渡
void push(T val){//入隊操作
p = new Node;
p->value = val;
if(head == NULL){
head = p;
}else{
tail->next = p;
}
tail = p;
length++;
}
int size(){//隊伍的大小
return length;
}
T pop(){//和stl標準庫的pop()函式不一樣,不僅可以刪除頭元素,還可以將頭元素的值返回
T value = head->value;
p = head;
head = head->next;
delete p;
length--;
return value;
}
T front(){//返回隊伍的隊首元素
return head->value;
}
bool empty(){//判斷隊伍是否為空
return length == 0;
}
void show(){//我自己加入的一個從隊首到隊尾的一個輸出展示函式
p = head;
while(p != NULL){
cout << p->value << " ";
p = p->next;
}
cout << endl;
}
}; int main(){
int n;
cin >> n;//n為楊輝三角的層數
Queue<int> queue;
for(int i = 1; i <= n; i++){//n層,所以迴圈n次
for(int j = 0; j < i - 2; j++){//這個請讀者自行體會,大概自己寫個三四層之後,就能夠明白其中的原理了
queue.push(queue.pop() + queue.front());//這句語句非常簡練,請讀者自行體會,我認為比課本上的更加簡潔一些
}
queue.push(1);//這是很關鍵的一步
queue.show();//運算結束,展示每一行
}
return 0;
}