/*************************************************************************
> File Name: stack.c
> Author: XXDK
> Email: v.manstein@qq.com
> Created Time: Tue 07 Mar 2017 04:22:40 AM PST
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
// 栈节点类型
struct stack_node {
int data;
struct stack_node* next;
};
// 栈头节点类型
struct stack_head {
struct stack_node* top; // 栈顶指针top
int n; // 栈深度
};
struct stack_head* create_empty_stack(void)
{
struct stack_head* head = (struct stack_head*)malloc(sizeof(struct stack_head));
printf("create ok.\n");
if(head == NULL) {
printf("allocate memory failed.");
}
head -> n = 0;
head -> top = NULL;
printf("create ok.\n");
return head;
}
int push_stack(struct stack_head * head, int data)
{
struct stack_node* node = (struct stack_node*)malloc(sizeof(struct stack_node));
if(node == NULL) {
printf("node allocate memory failed\n");
return -1;
}
printf("push ok\n");
node->data = data;
node->next = head->top;
head->top = node;
head->n++;
return 0;
}
int pop_stack(struct stack_head* head)
{
struct stack_node* temp;
if(head == NULL){
printf("stack invalid");
}
while(head->top != NULL) {
printf("[%d] ", head->top->data);
temp = head->top;
head->top = head->top->next;
free(temp);
}
return 0;
}
int get_stack_top(struct stack_head* head)
{
if(head == NULL) {
printf("stack invalid");
}
if(head->top == NULL) {
printf("stack empty.\n");
}else
return head->top->data;
}
int stack_empty(struct stack_head* head)
{
if(head == NULL) {
printf("stack invalid\n");
}
return (head->top == NULL) ? 0 : 1;
}
int main()
{
struct stack_head* head = create_empty_stack();
int a[] = {1,2,3,4,5,6};
for(int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
push_stack(head, a[i]);
}
pop_stack(head);
return 0;
}
C链栈基础
最新推荐文章于 2024-08-15 20:36:44 发布