链队的实现

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
typedef int ELEM_TYPE;



typedef struct Node
{
	ELEM_TYPE data;
	struct Node* next;
}Node,*PNode;
typedef struct PHead
{
	struct Node *front;
	struct Node *rear;
}Head,*Phead;


void Init_Queue(Phead pq);
bool Push(Phead pq, ELEM_TYPE val);
bool Pop(Phead pq, ELEM_TYPE* rtval);
bool Top(Phead pq, ELEM_TYPE* rtval);
int Get_length(Phead pq);
bool IsEmpty(Phead pq);
bool IsFull(Phead pq);
void Show(Phead pq);
void Destory(PHead pq);

void Init_Queue(Phead pq)
{
	assert(pq!= NULL);
	if (NULL==pq)
	{
		return;
	}
	pq->front = NULL;
	pq->rear = NULL;
}
bool Push(Phead pq, ELEM_TYPE val)
{
	assert(pq != NULL);
	Node* s = (Node*)malloc(sizeof(Node));
	if (NULL == s)exit(1);
	s->data = val;
	if (pq->rear == NULL)
	{
		s->next = NULL;
		pq->rear = s;
		pq->front = s;
	}
	else//里边已经又有一个节点
	{
		s->next = NULL;
		pq->rear->next = s;
		pq->rear = s;
	}
	return true;
}
bool Pop(Phead pq, ELEM_TYPE* rtval)
{
	assert(pq != NULL&&rtval!=NULL);
	Node* p = pq->front;
	if (pq->front == NULL)
	{
		return false;
	}
	if (pq->front->next == NULL)
	{
		*rtval = p->data;
		free(p);
		p = NULL;
		pq->front = pq->rear = NULL;
	}
	else
	{
		pq->front = p->next;
		*rtval = p->data;
		free(p);
		p = NULL;
	}
	return true;
}
bool Top(Phead pq, ELEM_TYPE* rtval)
{
	assert(pq != NULL && rtval != NULL);
	if (pq->front == NULL)
	{
		return false;
	}
	*rtval = pq->front->data;
	return true;
}
int Get_length(Phead pq)
{
	assert(pq != NULL);
	int count = 0;
	Node* p = pq->front;
	for (p; p != NULL; p = p->next)
	{
		count++;
	}
	return count;
}
bool IsEmpty(Phead pq)
{
   return pq->front==pq->rear==NULL;
}

void Destory(Phead pq)
{
	while (pq->front != NULL)
	{
		Node* p = pq->rear;
		pq->front = p->next;
		free(p);
		p = NULL;
	}
}
void Show(Phead pq)
{
	assert(pq != NULL);
	Node* p = pq->front;
	while (p != NULL)
	{
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

int main()
{
	Head pq;
	Init_Queue(&pq);
	for (int i = 0; i < 20; i++)
	{
		Push(&pq, i + 1);
	}
	Show(&pq);
	printf("\n");
	printf("%d ", Get_length(&pq));
	int tmp;
	Pop(&pq, &tmp);
	printf("\n");
	Show(&pq);
	printf("\n");
	printf("%d ", Get_length(&pq));
	printf("%d ", tmp);
	int tmp1;
	Top(&pq, &tmp1);
	printf("%d ", tmp1);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值