生活随笔
收集整理的這篇文章主要介紹了
用单链表实现一个队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
直接寫代碼吧
直接一些
#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
;
}
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 temp
->value
= value
;temp
->next
= s
->next
;s
->next
= temp
;#endifreturn SUCCESS
;
}
int stack_pop(StackInfo_st
*s
,ElementType
*value
)
{if(stack_is_empty(s
))return FAILURE
;*value
= s
->next
->value
;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
;
}
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");if(stack_is_empty(stack
)){int i
= 0;for(i
= 0 ;i
< 23;i
++){ printf("向隊列中放入第 [ %d ] 數(shù)據(jù)是 %d\n",i
,i
*3 + 7);stack_push(stack
,i
*3 +7);} }int topVal
;stack_top(stack
, &topVal
);printf("隊列頭部的數(shù)據(jù)是 %d\n",topVal
);int j
= 0;for(j
= 0;j
<25;j
++){int popVal
= 0;if(stack_pop(stack
, &popVal
) == SUCCESS
){printf("取出隊列第 [ %d ]個的 數(shù)據(jù) 是 [ %d ]\n",j
,popVal
);}}return 0;
}
總結(jié)
以上是生活随笔為你收集整理的用单链表实现一个队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。