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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
|
#include <stdio.h> #include <stdlib.h> #include <stdbool.h>
typedef int ElemType;
typedef struct node { ElemType data; struct node * pNext; } Node, *pNode;
typedef struct linkqueue { pNode pFront; pNode pRear; } LinkQueue, *pLinkQueue;
void InitQueue(pLinkQueue Q); bool EnQueue(pLinkQueue Q, ElemType elem); void Traverse(pLinkQueue Q); bool IsEmpty(pLinkQueue Q); bool DeQueue(pLinkQueue Q, ElemType * pElem); void DestoryQueue(pLinkQueue Q); void ClearQueue(pLinkQueue Q);
int main(void) { LinkQueue Q;
InitQueue(&Q);
printf("入队:"); EnQueue(&Q, 1); EnQueue(&Q, 2); EnQueue(&Q, 3); EnQueue(&Q, 4); EnQueue(&Q, 5); Traverse(&Q);
printf("出队:"); ElemType e; DeQueue(&Q, &e); DeQueue(&Q, &e); DeQueue(&Q, &e); Traverse(&Q);
return 0; }
void InitQueue(pLinkQueue Q) { pNode pHead = (pNode)malloc(sizeof(Node)); if ( NULL == pHead ) { printf("内存分配失败!"); exit(-1); } pHead->pNext = NULL;
Q->pFront = Q->pRear = pHead; }
bool EnQueue(pLinkQueue Q, ElemType elem) { pNode pNew = (pNode)malloc(sizeof(Node)); if ( NULL == pNew ) { printf("内存分配失败,无法入队!"); return false; } pNew->data = elem; pNew->pNext = NULL;
Q->pRear->pNext = pNew; Q->pRear = pNew;
return true; }
void Traverse(pLinkQueue Q) { pNode p = Q->pFront;
while ( p != Q->pRear ) { printf("%d ", p->pNext->data); p = p->pNext; } printf("\n"); }
bool IsEmpty(pLinkQueue Q) { return (Q->pFront == Q->pRear ); }
bool DeQueue(pLinkQueue Q, ElemType * pElem) { if ( IsEmpty(Q) ) { printf("队列为空,出队失败!"); return false; }
pNode p = Q->pFront;
*pElem = p->pNext->data; Q->pFront = p->pNext;
free(p); p = NULL;
return true; }
void DestoryQueue(pLinkQueue Q) { pNode p = Q->pFront;
while( p != NULL ) { Q = p->pNext; free(p); p = Q; } }
void ClearQueue(pLinkQueue Q) { pNode p = Q->pFront->pNext;
DestoryQueue(p); Q->pRear = Q->pFront; Q->pFront->pNext = NULL; }
|