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
}
}
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();
}