棧(C語言實現,基於鏈式結構)
Stack.h文件
/**
* 棧(C語言實現,基於鏈式結構)
* 指定數據類型為整型
*/
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
//定義棧節點的結構
typedef struct StackNode{
ElemType data;
struct StackNode* next;
}StackNode;
//定義棧的結構
typedef struct Stack{
StackNode* top;
int count;
}Stack;
/*
* 初始化一個空棧
*/
Status InitStack(Stack* s);
/*
* 銷毀棧
*/
Status DestroyStack(Stack* s);
/*
* 清空棧
*/
Status ClearStack(Stack* s);
/*
* 判斷棧是否為空
*/
Status StackEmpty(Stack s);
/*
* 獲取棧的長度
*/
int StackLength(Stack s);
/*
* 獲取棧頂元素
*/
Status GetTop(Stack s, ElemType* e);
/*
* 將元素壓入棧
*/
Status Push(Stack* s, ElemType e);
/*
* 將元素彈出棧
*/
Status Pop(Stack* s, ElemType* e);
/*
* 打印棧
*/
void PrintStack(Stack* s);
Stack.c文件
#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
Status InitStack(Stack* s)
{
s->top = NULL;
s->count = 0;
return OK;
}
Status DestroyStack(Stack* s)
{
StackNode* sn_tmp_ptr;
while(s->top){
sn_tmp_ptr = s->top;
s->top = s->top->next;
free(sn_tmp_ptr);
}
free(s);
}
Status ClearStack(Stack* s)
{
while(s->top){
s->top->data = 0;
s->top = s->top->next;
}
}
Status StackEmpty(Stack s)
{
return s.count<1 ? TRUE : FALSE;
}
int StackLength(Stack s)
{
return s.count;
}
Status GetTop(Stack s, ElemType* e)
{
*e = s.top->data;
return OK;
}
Status Push(Stack* s, ElemType e)
{
StackNode* snptr = (StackNode*)malloc(sizeof(StackNode));
snptr->data = e;
snptr->next = s->top;
s->top = snptr;
s->count++;
return OK;
}
Status Pop(Stack* s, ElemType* e)
{
*e = s->top->data;
StackNode* sn_tmp_ptr = s->top;
s->top = s->top->next;
s->count--;
free(sn_tmp_ptr);
return OK;
}
void PrintStack(Stack* s)
{
while(s->top){
printf("%d\n",s->top->data);
s->top = s->top->next;
}
}
int main()
{
Stack s;
ElemType e_tmp;
InitStack(&s);
printf("Is Stack empty : %d\n",StackEmpty(s));
Push(&s, 3);
Push(&s, 2);
Push(&s, 1);
Push(&s, 0);
Pop(&s, &e_tmp);
Pop(&s, &e_tmp);
printf("Is Stack empty : %d\n",StackEmpty(s));
PrintStack(&s);
printf("%d",s.count);
}
C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm
讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm
讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm
讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm
將C語言梳理一下,分布在以下10個章節中: