c stack

用一个头链表实现栈,头指针永远指向栈顶元素

#include <stdlib.h> #include <stdio.h> #include <string.h> typedef int ElemenType ; typedef struct node{ ElemenType data; struct node *next; }Linkstack; Linkstack *top; Linkstack *CreateStack() { Linkstack *s; s=(Linkstack*)malloc(sizeof(struct node)); s->next=NULL; return s; } int IsEmpty(Linkstack *s) { if(s->next==NULL) return 0; else return 1; } void push(Linkstack *s,ElemenType item) { Linkstack *n=(Linkstack*)malloc(sizeof(struct node)); n->data=item; n->next=s->next; s->next=n; } ElemenType pop(Linkstack *s) { if(s->next == NULL) return 0; ElemenType item=s->data; Linkstack *n=(Linkstack*)malloc(sizeof(struct node)); n=s->next; s->next=n->next; item=n->data; free(n); return item; } void VistStack(Linkstack *s) { Linkstack *p=(Linkstack*)malloc(sizeof(struct node)); p=s->next; while(p->next!=NULL) { printf("%d ",p->data); p=p->next; } printf("%d",p->data);//打印最后一个元素 } int main() { Linkstack *q; q=CreateStack(); push(q,10); push(q,11); push(q,8); push(q,13); push(q,7); push(q,9); VistStack(q); ElemenType z= pop(q); printf(" %d ",z); VistStack(q); return 0; }
原文地址:https://www.cnblogs.com/been/p/4227318.html