单链表实现一个队列

#include<stdio.h>
#include<stdlib.h>
typedef int ElementType; /队列元素类型/
#define SUCCESS 0
#define FAILURE -1
/定义队列结构/
typedef struct StackInfo
{
ElementType value; /队列存储的数据/
struct StackInfo *next; /指向队列的下一个元素/
}StackInfo_st;
/函数声明/
StackInfo_st *createStack(void);
int stack_push(StackInfo_st *s,ElementType value);
int stack_pop(StackInfo_st *s,ElementType *value);
int stack_top(StackInfo_st *s,ElementType *value);
int stack_is_empty(StackInfo_st *s);
/创建队列,外部释放内存/
StackInfo_st *createStack(void)
{
StackInfo_st *stack = (StackInfo_st *)malloc(sizeof(StackInfo_st));
if(NULL == stack)
{
printf(“malloc failed\n”);
return NULL;
}
stack->next = NULL;
return stack;
}
/入队列,0表示成,非0表示出错/
int stack_push(StackInfo_st *s,ElementType value)
{
/用来保存尾部指针/
StackInfo_st *tail = s;
StackInfo_st *temp = (StackInfo_st *)malloc(sizeof(StackInfo_st));
if(NULL == temp)
{
printf(“malloc failed\n”);
return FAILURE;
}

/*找到链表的尾部*/
while(s->next != NULL)
{
	s = s->next;
} 

temp->value = value;
temp->next = s->next;
s->next = temp;

#if 0 
/*将新的节点添加s->next前,使得s->next永远指向队列顶*/
temp->value = value;
temp->next = s->next;/*这一句是指向队列头部,实际上不用也没有问题*/
s->next = temp;
#endif
return SUCCESS;

}
/出队列/
int stack_pop(StackInfo_st *s,ElementType *value)
{
/首先判断队列是否为空/
if(stack_is_empty(s))
return FAILURE;
/找出队列顶元素/
*value = s->next->value;
/保存等下需要free的指针/
StackInfo_st *temp = s->next;
/更换队列顶的位置/
s->next = s->next->next;

/*释放队列顶节点内存*/
if(temp!=NULL)/*先判断指针是否为空*/
	free(temp);
temp = NULL;

return SUCCESS;

}
/访问队列顶元素/
int stack_top(StackInfo_st *s,ElementType *value)
{
/首先判断队列是否为空/
if(stack_is_empty(s))
{
return FAILURE;
}
*value = s->next->value;
return SUCCESS;
}
/判断队列是否为空,空返回1,未空返回0/
int stack_is_empty(StackInfo_st *s)
{
/队列顶指针为空,则队列为空/
if(s->next == NULL)
{
printf(“队列为空\n”);
return true;
}

return false; 

}
int main(void)
{

/*创建队列*/
StackInfo_st *stack = createStack();

printf("初始化队列头部\n");

/*如果队列为空,则压入元素1*/
if(stack_is_empty(stack))
{
	int i = 0;
	for(i = 0 ;i< 23;i++)
	{ 
    	printf("向队列中放入第 [ %d ] 数据是 %d\n",i,i*3 + 7);
    	stack_push(stack,i*3 +7);
    } 
}

/*访问队列顶元素*/
int topVal;
stack_top(stack, &topVal);
printf("队列头部的数据是 %d\n",topVal);

/*出队列*/
int j = 0;
for(j = 0;j<25;j++)
{
    int popVal = 0;
    if(stack_pop(stack, &popVal) == SUCCESS)
    {
    	printf("取出队列第 [ %d ]个的 数据 是 [ %d ]\n",j,popVal);
    }
}

/*最后记得将队列内存都释放,可自己尝试实现*/
return 0;

}

发布了28 篇原创文章 · 获赞 6 · 访问量 1518

猜你喜欢

转载自blog.csdn.net/lx123010/article/details/103806048