데이터 구조 -- 대기 열 - 체인 저장
12126 단어 데이터 구조
#include <stdio.h>
#include <stdlib.h>
typedef int elemType;
struct sNode{ /* */
elemType data;
struct sNode *next;
};
struct queueLK{
struct sNode *front; /* */
struct sNode *rear; /* */
};
/* 1. */
void initQueue(struct queueLK *hq)
{
hq->front = hq->rear = NULL;
return;
}
/* 2. */
void enQueue(struct queueLK *hq, elemType x)
{
struct sNode *newP;
newP = malloc(sizeof(struct sNode));
if(newP == NULL)
{
printf(" !
");
system("pause");
}
newP->data = x;
newP->next = NULL;
if(hq->rear == NULL)
{
hq->front = hq->rear = newP;
}else{
hq->rear->next = newP;
hq->rear = newP;
}
return;
}
/* 3. */
elemType outQueue(struct queueLK *hq)
{
if(hq->front == NULL)
{
printf(" ...
");
return -1;
}
struct sNode *temp = hq->front;
elemType data = temp->data;
if(hq->front == hq->rear) /* */
{
hq->front = hq->rear = NULL;
}else{
hq->front=hq->front->next;
}
free(temp);
return data;
}
/* 4. */
elemType peekQueue(struct queueLK *hq)
{
if(hq->front == NULL)
{
printf(" , .
");
return -1;
}
return hq->front->data;
}
/* 5. , 1, 0*/
int emptyQueue(struct queueLK *hq)
{
if(hq->front == NULL)
{
return 1;
}else{
return 0;
}
}
/* 6. */
void clearQueue(struct queueLK *hq)
{
if(hq->front == NULL)
{
return;
}
struct sNode *temp = hq->front;
while(hq->front != NULL)
{
hq->front = hq->front->next;
free(temp);
temp = hq->front;
}
hq->rear = NULL;
}
#if 1
int main()
{
struct queueLK hq;
int a[] = {2,4,5};
int i;
initQueue(&hq);
for(i = 0;i<sizeof(a)/4;i++)
{
enQueue(&hq,a[i]);
}
if(emptyQueue(&hq))
{
printf(" ...
");
}
printf(" :%d
",peekQueue(&hq));
printf(" :%d
",outQueue(&hq));
printf(" :%d
",outQueue(&hq));
printf(" :%d
",outQueue(&hq));
printf(" ...
");
enQueue(&hq,7);
printf(" :%d
",peekQueue(&hq));
clearQueue(&hq);
printf(" .
");
if(emptyQueue(&hq))
{
printf(" ...
");
}
system("pause");
return 0;
}
#endif
************************************************************************
실행 결과
************************************************************************
:2
:2
:4
:5
...
:7
.
...
. . .