队列的链式存储实现

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

typedef struct LinkNode{
    
    
	int data;
	LinkNode* next;
}LinkNode, *Queue;

typedef struct LQueue LinkQueue;

struct LQueue
{
    
    
	Queue front; 
	Queue rear;//队头 队尾 

};

LinkQueue* EnQueue(LinkQueue* S, int num)//入队 
{
    
    
	LinkNode* p = (LinkNode*)malloc(sizeof(LinkNode));
	if (p) {
    
    
		S->rear->next = p;//指向p,建立联系 
		S->rear = p;
		p->data = num;
		p->next = NULL;
	}
	return S;
}

LinkQueue* DeQueue(LinkQueue* S)//出队 
{
    
    
	if (S->front->next==NULL) {
    
    
		
		printf("\n队 列 为 空\n");
		return S;
	}
	else {
    
    
		LinkNode* p = S->front->next;
		S->front->next = S->front->next->next;
		printf("p->data = %5d\n", p->data);
		free(p);
		return S;
	}

}

int main()
{
    
    
	//建立头节点 
	LinkNode* head = (LinkNode*)malloc(sizeof(LinkNode));
	//建立初始头尾指针 
	LinkQueue* S = (LinkQueue*)malloc(sizeof(LinkQueue));
	if (S) {
    
    
		S->front = head;//初始化 
		S->rear = head; //初始化
	}


	int num;
	char ch;
	while (1) {
    
    
		printf("请输入需要入队的数:\t");
		scanf("%d", &num);
		S = EnQueue(S, num);
		printf("\n请确认是否继续入队?(停止入队选择空格+Enter)(继续直接按Enter)\n");
		getchar();
		if (ch = getchar() == ' ') {
    
    
			break;
		}
	}
	printf("\n是否进行出队操作?(选择:yes或no)\n");
	char b[4];
	scanf("%s", b);
	if(strcmp(b, "yes")==0){
    
    
	    while (1) {
    
    
		S = DeQueue(S);
		printf("\n请确认是否停止出队?(停止出队选择空格+Enter)(继续直接按Enter)\n");
        getchar();
		if (ch = getchar() == ' ') {
    
    
			break;
		}
	  }
	}
	free(head);
	return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_52001969/article/details/113312430