Skip to content

Commit

Permalink
Merge pull request #65 from doyo2024/main
Browse files Browse the repository at this point in the history
fix: bug when push an element into an empty queue
  • Loading branch information
dx3906999 authored Nov 25, 2024
2 parents d64f112 + 49d822b commit cae55ec
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
18 changes: 17 additions & 1 deletion posts/2024/2_advanced_C/code/ds_s3/queue.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ void Init();
ElemType Front();
ElemType Pop();
void Push(ElemType data);
void Print();

int main()
{
Expand All @@ -38,6 +39,10 @@ int main()
} else if (!strcmp(inst, "push")) {
scanf("%d", &data);
Push(data);
} else if (!strcmp(inst, "print")) {
Print();
} else if (!strcmp(inst, "exit")) {
break;
} else {
printf("Error: Undefined Instruction.\n");
}
Expand Down Expand Up @@ -83,10 +88,21 @@ void Push(ElemType data) {
struct node * ptr = NewSpace;
ptr->data = data;
ptr->next = NULL;
if (QueueTail == NULL) {
if (QueueHead == NULL) {
QueueHead = QueueTail = ptr; // 注意如果队列本来是空的,要把队头也指向新元素
} else {
QueueTail->next = ptr; // 由于是从队尾入队,所以注意指针的指向
QueueTail = ptr;
}
}

void Print() {
struct node *now = QueueHead;
int cnt = 0;
while (now != NULL) {
cnt++;
printf("%d ", now->data);
now = now->next;
}
printf("\nThere are %d elements in the list.\n", cnt);
}
8 changes: 4 additions & 4 deletions posts/2024/2_advanced_C/ds_s3.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ Author: [doyo](https://github.com/doyo2024)

## 队列的实现

下面基于[上上份讲义](https://ucas-ctf.github.io/posts/2024/2_advanced_C/ds_s1)中的单向链表给出栈的一种实现。正如前文所述,队列实际上也是一种特殊的线性表,所以只需要对单向列表的实现略作修改,使其插入仅在其一端、删除在另一端进行即可。
下面基于[上上份讲义](https://ucas-ctf.github.io/posts/ds_s1)中的单向链表给出栈的一种实现。正如前文所述,队列实际上也是一种特殊的线性表,所以只需要对单向列表的实现略作修改,使其插入仅在其一端、删除在另一端进行即可。

&emsp;&emsp;完整代码详见<a href="https://ucas-ctf.github.io/posts/2024/2_advanced_C/code/ds_s3/queue.c" download="queue.c">此处(点击下载)</a>。
&emsp;&emsp;完整代码详见<a href="https://ucas-ctf.github.io/posts/code/ds_s3/queue.c" download="queue.c">此处(点击下载)</a>。

### 队列的必要元素

Expand Down Expand Up @@ -62,7 +62,7 @@ void Push(ElemType data) {
struct node * ptr = NewSpace;
ptr->data = data;
ptr->next = NULL;
if (QueueTail == NULL) {
if (QueueHead == NULL) {
QueueHead = QueueTail = ptr; // 注意如果队列本来是空的,要把队头也指向新元素
} else {
QueueTail->next = ptr; // 由于是从队尾入队,所以注意指针的指向
Expand Down Expand Up @@ -93,4 +93,4 @@ ElemType Pop() {

## 扩展:用数组实现队列

不仅仅是栈可以用数组实现,队列也是可以的。请参考[这篇讲义](https://ucas-ctf.github.io/posts/2024/2_advanced_C/ds_ex2)
不仅仅是栈可以用数组实现,队列也是可以的。请参考[这篇讲义](https://ucas-ctf.github.io/posts/ds_ex2)

0 comments on commit cae55ec

Please sign in to comment.