链队的练习

链队的练习

相关内容:队列的链式存储结构(链队)

//链队的初始化、入队、出队、取对头
#include<stdio.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
typedef int Status;
//结点结构
typedef struct QNode{
    
    	
	int data;		//结点数据域
	struct QNode *next;	//结点指针域
}QNode,*QueuePtr;	//指向队中结点的指针QueuePtr
//链队结构
typedef struct{
    
    		
	QueuePtr front;	//队头指针,指向队列头结点
	QueuePtr rear;	//队尾指针,指向队列尾结点
}LinkQueue; //链队指针
//初始化:新建头结点、将队头和队尾指针指向头结点
Status InitLinkQueue(LinkQueue *LQ){
    
    
    QueuePtr p;//新建头结点
    p=(QNode*)malloc(sizeof(QNode));
    p->next=NULL;//头结点指针域置空
    LQ->front=LQ->rear=p;//队头和队尾指针指向头结点
    return OK;
}
//入队限定在队尾操作
Status EnLinkQueue(LinkQueue *LQ,int e){
    
    
    QueuePtr s;//新建结点
    s=(QNode*)malloc(sizeof(QNode));
    s->data=e;
    s->next=NULL;
    //尾插操作
    LQ->rear->next=s;//原队尾结点指向新结点
    LQ->rear=s;//后移队尾指针,将新结点作为新队尾
    return OK;
}
//出队限定在队头操作
Status DeLinkQueue(LinkQueue *LQ,int *e){
    
    
    if (LQ->front==LQ->rear)//判空
        return ERROR;
    QueuePtr p;//指向队中结点的指针p
    //LQ->front指向头结点,LQ->front->next指向首元结点
    p=LQ->front->next;//让p指向首元结点
    *e=p->data;//取出队头元素
    LQ->front->next=p->next;//头结点的指针域指向待删结点的下一个结点
    if (LQ->rear==p)//如果待删首元结点p为最后一个结点
        LQ->rear=LQ->front;//恢复初始状态
    free(p);//删除首元结点
    return OK;
}
int GetHead(LinkQueue *LQ){
    
    
    if (LQ->front != LQ->rear)
        return LQ->front->next->data;//首元结点数据
    return ERROR;
}
int main(){
    
    
    int n,e;
    LinkQueue LQ;
    InitLinkQueue(&LQ);
    printf("Init Completed!\n");
    printf("输入入队元素个数:");
    scanf("%d",&n);
    for (size_t i = 0; i < n; i++)
    {
    
    
        printf("输入第%d个入队元素:",i+1);
        scanf("%d",&e);
        EnLinkQueue(&LQ,e);
    }
    printf("队头元素:%d\n",GetHead(&LQ));
    for (size_t i = 0; i < n; i++)
    {
    
    
        printf("输出第%d个出队元素:",i+1);
        DeLinkQueue(&LQ,&e);
        printf("%d\n",e);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_48524215/article/details/134233225