栈——栈的顺序存储结构设计思路与实现

 

 

总的实现代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAXSIZE 100
typedef char string[MAXSIZE];

typedef struct stu{
	string name;
	string id;
}ElemType;

typedef struct _stack{
	ElemType* data;
	int size;
	int maxSize;
}STACK;

// 初始化栈
STACK* InitStack(STACK* stack, int size) 
{
	stack = (STACK *)malloc(sizeof(STACK)); 
	if(stack == NULL)
	    return NULL;
	stack->data = NULL;
    stack->data = (ElemType *)malloc(sizeof(ElemType) * size);
    if(stack->data == NULL)
    {
        free(stack);
		return NULL;	
    }
    stack->maxSize = size;
    stack->size = 0;
    return stack;
}

// 判断栈是否为空
bool Empty(STACK* stack) 
{
    return stack->size == 0;
}

// 判断栈是否满
bool Full(STACK* stack) 
{
    return stack->size == stack->maxSize;
}

// 入栈
bool Push(STACK* stack, ElemType item) 
{
    if (Full(stack)) 
        return false;
    stack->data[stack->size++] = item;
    return true;
}

// 出栈
bool Pop(STACK* stack) 
{
    if (Empty(stack)) 
	{
        return false;
    }
    stack->size--;
    return true;
}

// 查看栈顶元素
ElemType* Top(STACK* stack) 
{
    if (Empty(stack)) 
	{
        return NULL;
    }
    return &(stack->data[stack->size - 1]);
}

int Size(STACK* stack)
{
	if(stack == NULL)
	    return 0;
	    
	return stack->size;
}

int main() 
{
    STACK *stack = NULL;
    stack = InitStack(stack, 100);
    ElemType arr[20] = {
	    {"张三", "0x001"},
	    {"李四", "0x002"}
	};
    Push(stack, arr[0]);
    Push(stack, arr[1]);
    
    ElemType e = *(Top(stack));
    printf("栈顶元素为:%s  %s\n", e.name, e.id);
    printf("栈中元素个数为:%d\n", Size(stack)); 
    
    Pop(stack);
    printf("栈中元素个数为:%d\n", Size(stack));
    e = *(Top(stack));
    printf("栈顶元素为:%s  %s\n", e.name, e.id);
    
    if(Empty(stack))
	{
		printf("栈空\n");
    }
    else
    {
    	printf("栈非空\n");
	}
	
	if(Full(stack))
	{
		printf("栈满"); 
	}
	else
	{
		printf("栈非满\n"); 
	}
	
    // 销毁栈 
    free(stack);

    return 0;
}

 

请登录后发表评论

    没有回复内容