實作資結(2) – Linear Queue
用Array實作:
//用Array製作一個Linear Queue
#include <iostream>
using namespace std;
struct Queue{
int max_size;
int head = 0;
int tail = 0;
int *elements;
Queue(int size){
//初始化
elements = new int[size];
max_size = size;
}
bool isFull(){
if(tail == max_size) return true;
return false;
}
bool isEmpty(){
if(head == tail) return true;
return false;
}
void Enqueue(int a) {
if(isFull()){
cout << "Queue was full!" << endl;
}else{
elements[tail++] = a;
}
}
void Dequeue() {
if(head == tail){
cout << "Queue was empty!" << endl;
}else{
cout << "Deleted " << elements[head++] << endl;
}
}
int First() {
return elements[head];
}
void Show(){
for(int i = head; i < tail;i++){
cout<< elements[i];
}
cout << endl;
}
};
int main (){
Queue q(3);
q.Enqueue(1);
q.Show();
q.Enqueue(2);
q.Show();
q.Enqueue(3);
q.Show();
q.Enqueue(4);
q.Show();
q.Dequeue();
q.Show();
q.Dequeue();
q.Show();
q.Dequeue();
q.Show();
q.Dequeue();
q.Show();
return 0;
}
用Linked List實作:
//用Linked List製作一個Linear Queue
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next = NULL;
Node(int d){
data = d;
}
};
struct Queue{
Node *head;
Node *tail = head;
int getLength(){
if(head == NULL) return 0;
int result = 1; //HEAD也佔一格
Node *t = head;
while(t->next != NULL){
result++;
t = t->next;
}
return result;
}
bool isEmpty(){
if(head == tail) return true;
return false;
}
void Enqueue(int a) {
if(isEmpty()){
head = new Node(-1);
tail = new Node(a);
head->next = tail;
}else{
tail->next = new Node(a);
tail = tail->next;
}
}
void Dequeue() {
if(head->next != NULL){
Node *tmp = head;
head = head->next;
free(tmp);
}
}
int First() {
if(head->next != NULL){
return head->next->data;
}
return -1; //表示Queue為空
}
void Show(){
Node *t = head;
while(t->next != NULL){
t = t->next;
cout << t->data << ' ';
}
cout << endl;
}
};
int main (){
Queue q;
q.Enqueue(1);
q.Show();
q.Enqueue(2);
q.Show();
q.Enqueue(3);
q.Show();
q.Enqueue(4);
q.Show();
q.Dequeue();
q.Show();
q.Dequeue();
q.Show();
q.Dequeue();
q.Show();
q.Dequeue();
q.Show();
return 0;
}
Filed under: c++,資結 - @ 2021 年 7 月 22 日 下午 12:12
標籤: c++, data_struct