C语言实现栈

    xiaoxiao2023-11-08  142

    第一次自己实现栈,有一些激动呢!!!

    进栈

     

    #include<stdio.h> #include<stdlib.h> typedef struct node{ int elem; struct node *next; }DataNode; typedef struct { int count; DataNode *next; }*LinkHead,Linkstack; int Init(LinkHead *S) { LinkHead p=(LinkHead)malloc(sizeof(Linkstack)); p->next = NULL; p->count = 0; (*S) = p; return 0; } int EnStack(LinkHead *S,int elem) { DataNode *p = (DataNode *)malloc(sizeof(DataNode)); p->elem = elem; p->next = (*S)->next; (*S)->next = p; (*S)->count += 1; return 0; } int DeStack(LinkHead *S,int *elem){ if(*S==NULL) { return -1; } DataNode *p=(*S)->next; *elem = p->elem; (*S)->next = p->next; free(p); (*S)->count -= 1; return 0; } int Clear(LinkHead *S) { while((*S)->next!=NULL) { DataNode *p=(DataNode *)malloc(sizeof(DataNode)); p = (*S)->next; (*S)->next = p->next ; free(p); (*S)->count -= 1; } (*S)->next = NULL; (*S)->count = 0; return 0; } int Destory(LinkHead *S) { Clear(S); free(*S); (*S)=NULL; return 0; } int Traverse(LinkHead S) { DataNode *p=S->next ; for(int i=0;i<S->count;i++) { printf("%d ",p->elem); p=p->next; } return 0; } int main() { LinkHead S; Init(&S); int n; scanf("%d",&n); for(int i=0;i<n;i++){ int m; scanf("%d",&m); EnStack(&S,m); } Traverse(S); int elem; DeStack(&S,&elem); printf("\n%d\n",elem); DeStack(&S,&elem); printf("\n%d\n",elem); Traverse(S); Clear(&S); printf("\n"); Traverse(S); printf("\n"); return 0; }

     

    最新回复(0)