clist

c语言实现队列

栈的理解

队列(Queue)需要两个特征描述,队头(front)和队尾(rear),顾名思义,排队时后来者应跟在队尾,最前面的人应当最先出队

队列实现

数组实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 3
int arr[MAX];
int front, rear;
bool isEmpty(){
return (front == -1 && rear == -1) ? true : false;
}

bool isFull(){
return (rear+1)%MAX == front ? true : false;
}

void enQueue(int x){
if(isFull()){
printf("queue is full\n");
return;
}
if(isEmpty())
front = rear = 0;
else
rear = (rear+1)%MAX;
arr[rear] = x;
}
void deQueue(){
if(isEmpty())
{
printf("queue is empty\n");
return;
}
else if(front == rear)
front = rear = -1;
else
front = (front+1)%MAX;

}

void Print(){
int length = (rear + MAX - front)%MAX + 1;
int i;
for( i = 0; i<length;i++)
{
printf("%d ", arr[(front+i)%MAX]);
}
printf("\n");
}

int main(){
front = -1;
rear = -1;
enQueue(2); Print();
enQueue(4); Print();
enQueue(6); Print();
deQueue(); Print();
enQueue(10); Print();
return 0;
}

链表实现(这是真没用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Two glboal variables to store address of front and rear nodes.
struct Node* front = NULL;
struct Node* rear = NULL;

// To Enqueue an integer
void Enqueue(int x) {
struct Node* temp =
(struct Node*)malloc(sizeof(struct Node));
temp->data =x;
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}

// To Dequeue an integer.
void Dequeue() {
struct Node* temp = front;
if(front == NULL) {
printf("Queue is Empty\n");
return;
}
if(front == rear) {
front = rear = NULL;
}
else {
front = front->next;
}
free(temp);
}

int Front() {
if(front == NULL) {
printf("Queue is empty\n");
return 0;
}
return front->data;
}

void Print() {
struct Node* temp = front;
while(temp != NULL) {
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}

int main(){
/* Drive code to test the implementation. */
// Printing elements in Queue after each Enqueue or Dequeue
Enqueue(2); Print();
Enqueue(4); Print();
Enqueue(6); Print();
Dequeue(); Print();
Enqueue(8); Print();
}


clist
http://example.com/2023/12/11/数据结构/clist/
作者
bradin
发布于
2023年12月11日
许可协议