基于链式存储的栈

来源:互联网 发布:linux内网ip映射到外网 编辑:程序博客网 时间:2024/06/07 06:46

1.顺序结构:数据元素存放在一段连续的地址空间中

   优点:随机访问速度快

   缺点:插入、删除速度慢,空间利用率低

2.链式结构;数据存放在彼此独立的地址空间

    优点:空间利用率高,插入和删除方便

    缺点:随机访问速度慢

/* stack_base_list.h */

#ifndef __STACK_BASE_LIST_H__
#define __STACK_BASE_LIST_H__

/* express the node in the stack*/
typedef struct StackNode
{
int data;//data
struct StackNode *next;//point to the next node
}STACK_NODE;

typedef struct Stack
{
STACK_NODE *top;
}STACK;

/* create a stack*/
STACK *stack_create(void);

/* destroy the stack*/
void stack_destroy(STACK *stack);

/* clear the stack*/
void stack_clear(STACK *stack);

/* Is the stack empty?*/
int stack_empty(STACK *stack);

/* Is the stack full?*/
int stack_full(STACK *stack);

/*create a new node*/
STACK_NODE *node_create(int data, STACK_NODE *next);

/*destroy an old node*/
void node_destroy(STACK_NODE *node);

/* push */
void stack_push(STACK *stack, int data);

/* pop */
int stack_pop(STACK *stack);

#endif


/* stack_base_list.c */

#include <stdio.h>
#include <stdlib.h>
#include "stack_base_list.h"

/* create a stack*/
STACK *stack_create(void)
{
STACK *stack = (STACK *)malloc(sizeof(STACK));
if(stack == NULL)
return NULL;
stack->top = NULL;
return stack;
}

void stack_clear(STACK *stack)
{
STACK_NODE *p_temp = NULL;
while(stack->top)
{
p_temp = stack->top->next;
node_destroy(stack->top);
stack->top = p_temp;
}
}

/* destroy the stack*/
void stack_destroy(STACK *stack)
{
stack_clear(stack);
free(stack);
stack = NULL;
}

/* Is the stack empty?*/
int stack_empty(STACK *stack)
{
return !stack->top;
}

/* Is the stack full?*/
int stack_full(STACK *stack)
{
return 0;
}

/*create a new node*/
STACK_NODE *node_create(int data, STACK_NODE *next)
{
STACK_NODE *node  = (STACK_NODE *)malloc(sizeof(STACK_NODE));
if(node == NULL)
return NULL;
node->next = next;
node->data = data;
return node;
}

/*destroy an old node*/
void node_destroy(STACK_NODE *node)
{
free(node);
node = NULL;
}

/* push */
void stack_push(STACK *stack, int data)
{
stack->top = node_create(data, stack->top);
}

/* pop */
int stack_pop(STACK *stack)
{
int temp =  stack->top->data;
STACK_NODE *p_next = stack->top;
stack->top = stack->top->next;
node_destroy(p_next);
return temp;
}

/* stack_base_list_test.c */

#include <stdio.h>
#include <stdlib.h>
#include "stack_base_list.h"


int main()
{
int num = 1;
int data = 0;
int scale = 0;
STACK *stack = stack_create();
if(stack == NULL)
return 0;

printf("Please input the data and scale:");
scanf("%d%d", &data, &scale);
while(data != 0)
{
stack_push(stack, data%scale);
printf("%d",data%scale);
data = data/scale;
}
printf("\n");
while(!stack_empty(stack))
{
printf("%d", stack_pop(stack));
}
printf("\n");
stack_destroy(stack);
return 0;
}



0 0
原创粉丝点击