C语言实现栈
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
/*
栈的链式实现
*/
typedef int ElemType;
typedef struct Node{
ElemType elem;
struct Node *next;
}Node;
typedef struct Stack{
Node *top;
}Stack;
void init(Stack *stack);
void destroy(Stack *stack);
bool isEmpty(Stack *stack);
void push(Stack *stack, ElemType elem);
int pop(Stack *stack);
void traverse(Stack *stack);
int main()
{
Stack *stack;
init(&stack);
push(&stack,1);
push(&stack,2);
push(&stack,3);
push(&stack,4);
traverse(&stack);
printf("\n");
printf("删除的栈顶元素为:%d\n",pop(&stack));
traverse(&stack);
destroy(&stack);
return 0;
}
void init(Stack *stack){
Node *node = (Node*)malloc(sizeof(Node));
node->next = NULL;
stack->top = node;
}
void destroy(Stack *stack){
Node *node = stack->top;
while(node->next != NULL){
free(node);
node = node->next;
}
free(stack->top);
stack->top = NULL;
}
bool isEmpty(Stack *stack){
Node *node = stack->top->next;
if(node == NULL){
return true;
}else{
return false;
}
}
/*
入栈:使用的是链表的头插法的思想
1.为须要插入的节点分配内存空间
2.将须要插入的元素赋给新节点的值域
3.将头结点的下一个节点赋值给新节点的下一个节点
4.将新节点赋值给头结点的下一个节点
*/
void push(Stack *stack, ElemType elem){
Node *node = (Node*)malloc(sizeof(Node));
node->elem = elem;
node->next = stack->top->next;
stack->top->next = node;
}
/*
出栈:使用的是链表的头删除思想
1.将须要删除的节点取出,赋值给一个暂时变量
2.将须要删除的节点的下
一个节点赋值给须要删除的节点的上一个节点的下一个
3.free掉须要删除的节点就可以
*/
int pop(Stack *stack){
assert(!isEmpty(&stack));
Node *new_node = stack->top->next;
ElemType elem = new_node->elem;
stack->top->next = new_node->next;
free(new_node);
return elem;
}
void traverse(Stack *stack){
Node *node = stack->top;
while(node->next != NULL){
printf("%d ",node->next->elem);
node = node->next;
}
}
posted on 2017-08-17 13:51 gavanwanggw 阅读(112) 评论(0) 收藏 举报
浙公网安备 33010602011771号