第三节、队列
1.队列的实现
(1)队列的定义以及结构体
队列可以理解为先入先出,一端进一端出。这里使用链表的头进尾出。它的结构体为:
1 2 3 4 5
| typedef struct Line { Elemtype data; struct Line* next; }*LinkLine;
|
(2)队列的基本操作的实现
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <stdio.h> #include <corecrt_malloc.h>
#define Elemtype int
typedef struct Line { Elemtype data; struct Line* next; }*LinkLine;
void Init(LinkLine &head) { head = NULL; }
void Inline(LinkLine& p, Elemtype x) { LinkLine s = (LinkLine)malloc(sizeof(Line)); s->data = x; if (p) { s->next = p; } else { s->next = NULL; } p = s; }
void Outline(LinkLine &head, Elemtype &x) { LinkLine p = head; LinkLine q = p; while (p->next) { q = p; p = p->next; } x = p->data; q->next = NULL; free(p); }
void Print(LinkLine head) { LinkLine p = head; while (p) { printf("%d ", p->data); p = p->next; } }
int main() { LinkLine head; Init(head); for (int i = 1; i < 5; i++) { Inline(head, i); } printf("-----------------------\n"); Print(head); int x = 0; printf("\n-----------------------\n"); Outline(head, x); printf("%d", x); printf("\n-----------------------\n"); Print(head); printf("\n-----------------------\n"); }
|