數據結構之—棧
順序棧
內部採用數組實現
結構圖;
定義結構體:
typedef struct StackInfo
{
int topOfStack; /*記錄棧頂位置*/
ElementType stack[STACK_SIZE]; /*棧數組,也可以使用動態數組實現*/
}StackInfo_st;
函數聲明
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_full(StackInfo_st *s);
int stack_is_empty(StackInfo_st *s)
進棧以及出棧
圖示:
int stack_push(StackInfo_st *s,ElementType value)
{
if(stack_is_full(s))
return FAILURE;
/*先增加topOfStack,再賦值*/
s->topOfStack++;
s->stack[s->topOfStack] = value;
return SUCCESS;
}
int stack_pop(StackInfo_st *s,ElementType *value)
{
/*首先判斷棧是否爲空*/
if(stack_is_empty(s))
return FAILURE;
*value = s->stack[s->topOfStack];
s->topOfStack--;
return SUCCESS;
}
其餘操作
/*訪問棧頂元素*/
int stack_top(StackInfo_st *s,ElementType *value)
{
/*首先判斷棧是否爲空*/
if(stack_is_empty(s))
return FAILURE;
*value = s->stack[s->topOfStack];
return SUCCESS;
}
/*判斷棧是否已滿,滿返回1,未滿返回0*/
int stack_is_full(StackInfo_st *s)
{
return s->topOfStack == STACK_SIZE - 1;
}
/*判斷棧是否爲空,空返回1,非空返回0*/
int stack_is_empty(StackInfo_st *s)
{
return s->topOfStack == - 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);
進棧以及出棧
圖示:
int stack_push(StackInfo_st *s,ElementType value)
{
StackInfo_st *temp = malloc(sizeof(StackInfo_st));
if(NULL == temp)
{
printf("malloc failed\n");
return FAILURE;
}
/*將新的節點添加s->next前,使得s->next永遠指向棧頂*/
temp->value = value;
temp->next = s->next;
s->next = temp;
return 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;
/*釋放棧頂節點內存*/
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)
{
/*棧頂指針爲空,則棧爲空*/
return s->next == NULL;
}