C 数据结构:栈的链式存储
一、实现
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data_;
struct node* next_;
}Node;
typedef struct stack
{
Node *top_;
}Stack;
void initStack(Stack *stack);
void push(Stack *stack, int data);
int pop(Stack *stack);
int isEmpty(Stack *stack);
void destoryStack(Stack *stack);
int main()
{
Stack s;
initStack(&s);
for (int i = 0; i<4; ++i)
{
push(&s, i);
}
while (!isEmpty(&s))
printf("%2d", pop(&s));
puts("");
destoryStack(&s);
return 0;
}
void initStack(Stack *stack)
{
stack->top_ = (Node*)malloc(sizeof(Node));
if (NULL == stack->top_)
exit(-1);
stack->top_->next_ = NULL;
}
void push(Stack *stack, int data)
{
Node *ptr = (Node*)malloc(sizeof(Node));
if (NULL == ptr)
exit(-1);
ptr->data_ = data;
ptr->next_ = stack->top_->next_;
stack->top_->next_ = ptr;
}
int pop(Stack *stack)
{
Node *tmp = stack->top_->next_;
int tmpData = tmp->data_;
stack->top_->next_ = tmp->next_;
free(tmp);
tmp = NULL;
return tmpData;
}
int isEmpty(Stack *stack) { return NULL == stack->top_->next_; }
void destoryStack(Stack *stack)
{
while (!isEmpty(stack))
pop(stack);
free(stack->top_);
stack->top_ = NULL;
}

二、过程演示
