1.3 - Stack and Queue
使用Stack製作Queue演算法、使用Queue製作Stack演算法
1. 使用2個Stack製作Queue(Linklist)
概念示意圖:

1.1 Stack的pop()
int pop(stack **st){ //透過雙重指標改變指標變數的值
stack *temp = *st; //用來儲存stack的top節點
if (IsEmpty(st) == 1){
printf("The stack is empty.\n");
return -100;
}
else{
*st = temp->next;
}
return temp->Data;
}
1.2 Stack的push()
void push(stack **st, int data){ //透過雙重指標改變指標變數的值
stack *new_node = (stack *)malloc(sizeof(stack));
// save the data to the new node
new_node->Data = data;
new_node->next = NULL;
if (IsEmpty(st) == 1){
*st = new_node;
}
else{
new_node->next = *st; // the origin head is the older node
*st = new_node; // the lastest data is the top node
}
}
1.3 Queue的enqueue()
void enqueue(int data){
push(&s1, data); //改變s1的指標
}
1.4 Queue的enqueue()
int dequeue(){
int output;
if (IsEmpty(&s1) == 1){
printf("The stack is empty.\n");
return 0;
}
else{ //執行概念示意圖的運作
while(IsEmpty(&s1)!=1)
push(&s2, pop(&s1));
output = pop(&s2);
while(IsEmpty(&s2)!=1)
push(&s1, pop(&s2));
return output;
}
return -1;
}
1.5 執行結果:
Enqueue: 1, 2, 3
//front(1, 2, 3)rear
Dequeue: 1
Dequeue: 2
Enqueue: 4
//front(3, 4)rear
Dequeue: 3
完整程式碼: https://github.com/gary30404/Data-Structure/blob/master/1/1.4/queue_by_stack_in_linklist.c
2. 使用1個Queue製作Stack(Linklist)
概念示意圖:

2.1 Queue的dequeue()
和用Linklist做的Queue相同。
int dequeue(){
if (isEmpty() == 1){
printf("The queue is empty.\n");
return 0;
}
else{
queue *output = front;
front = front->next; // the older data
return output->Data; // return the top node
}
return -1;
}
2.2 Queue的enqueue()
和用Linklist做的Queue相同。
void enqueue(int data){
// request space for new node
queue *new_node = (queue *)malloc(sizeof(queue));
// save the data to the new node
new_node->Data = data;
new_node->next = NULL;
// push to the back of the queue
if (isEmpty() == 1){
front = new_node;
rear = front;
}
else{
rear->next = new_node; // next of the rear node points to new node
rear = new_node;
}
}
2.3 Stack的pop()
int pop(queue *q){
queue *temp = q;
if (q == NULL)
printf("The stack is empty.\n");
else{
int ln = 0;
while(q != NULL){ //計算Queue的大小
ln++;
q = q->next;
}
for (int i = 0; i<ln-1; i++){ //將n-1個資料dequeue()後再enqueue(),讓最後輸入的資料在Queue的front端
int t = dequeue();
enqueue(t);
}
}
return dequeue();
}
2.4 Stack的push()
void push(int data){
enqueue(data); //將資料存到Queue中
}
2.5 執行結果:
Push: 1, 2, 3
//(1, 2, 3)top
Pop: 3
Pop: 2
//(1)top
Push: 4, 5
//(1, 4, 5)top
Pop: 5
完整程式碼: https://github.com/gary30404/Data-Structure/blob/master/1/1.4/stack_by_queue_in_linklist.c
Last updated