meridian00 2019-11-05
#include <stdlib.h> #include <stdio.h> typedef int data_t; //类型 typedef struct node{ data_t data; struct node* next; }linkstack_t; //创建 linkstack_t* create_stack() { linkstack_t* stack=malloc(sizeof(linkstack_t)); stack->next=NULL; return stack; } //判空 int isnull_stack(linkstack_t* stack) { if(stack==NULL) return 0; return stack->next==NULL; } //入栈 int push_stack(linkstack_t* stack,data_t data) { if(stack==NULL) return -1; linkstack_t* newnode=create_stack(); newnode->data=data; newnode->next=stack->next; stack->next=newnode; return 0; } //出栈 int pop_stack(linkstack_t* stack, data_t* data) { if(stack==NULL||isnull_stack(stack)||data==NULL) return -1; linkstack_t* temp=stack->next; stack->next=temp->next; *data=temp->data; free(temp); return 0; } //看一眼 int view_stack(linkstack_t* stack) { if(stack==NULL||isnull_stack(stack)) return -1; printf("%3d ",stack->next->data); return 0; } //长度 int length_stack(linkstack_t* stack) { if(stack==NULL||isnull_stack(stack)) return 0; int sum=0; while(stack->next!=NULL) { sum++; stack=stack->next; } return sum; } //清空 int clear_stack(linkstack_t* stack) { if(stack==NULL||isnull_stack(stack)) return -1; data_t data; while(!isnull_stack(stack)) { pop_stack(stack,&data); } return 0; } //销毁 int destroy_stack(linkstack_t* stack) { if(stack==NULL) return -1; if(!isnull_stack(stack)) clear_stack(stack); free(stack); return 0; } //打印(真) int print_stack(linkstack_t* stack) { if(stack==NULL||isnull_stack(stack)) return -1; linkstack_t* temp=create_stack(); data_t data; while(!isnull_stack(stack)) { view_stack(stack); pop_stack(stack,&data); push_stack(temp,data); } printf("\n"); while(!isnull_stack(temp)) { pop_stack(temp,&data); push_stack(stack,data); } destroy_stack(temp); return 0; } //逆打印(真) // int reprint_stack(linkstack_t* stack) { if(stack==NULL||isnull_stack(stack)) return -1; linkstack_t* temp=create_stack(); data_t data; while(!isnull_stack(stack)) { // view_stack(stack); pop_stack(stack,&data); push_stack(temp,data); } // printf("\n"); while(!isnull_stack(temp)) { view_stack(temp); pop_stack(temp,&data); push_stack(stack,data); } printf("\n"); destroy_stack(temp); return 0; } int main(int argc, const char *argv[]) { linkstack_t* stack=create_stack(); int i; for(i=1;i<=20;i++) { push_stack(stack,i*5); print_stack(stack); } reprint_stack(stack); print_stack(stack); printf("length_stack:%d\n",length_stack(stack)); clear_stack(stack); printf("length_stack:%d\n",length_stack(stack)); destroy_stack(stack); return 0; }