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;
}