LinStack.h // 堆栈的链式表示 #include "stdio.h" #include "stdlib.h" typedef struct snode { DataType data; struct snode *next; } LSNode; void StackInitiate(LSNode ** head) { if (( *head = (LSNode *)malloc(sizeof(LSNode))) == 0 ) exit(1); (*head)->next = NULL; } int StackNotEmpty(LSNode * head) { if (head->next == NULL) { return 0; } else { return 1; } } int StackPush(LSNode * head, DataType d) { LSNode *p; if ( (p = (LSNode *)malloc(sizeof(LSNode))) == NULL ) { printf("内存不足无法插入!/n"); return 0; } p->data = d; p->next = head->next; //p插在head这里 head->next = p; return 1; } int StackPop(LSNode * head, DataType *d) { LSNode *p = head->next; if (p == NULL) { printf("堆栈已空!/n"); return 0; } //不用else也行 *d = p->data; head->next = p->next; free(p); return 1; } int StackTop(LSNode * head, DataType *d) { LSNode *p = head->next; if (p == NULL) { printf("栈堆空了!/n"); return 0; } *d = p->data; return 1; } void Destroy(LSNode * head) { LSNode *p, *q; p = head; while(p != NULL) { q = p; p = p->next; free(q); } } LinStackApp1.cpp #include "stdio.h" #include "stdlib.h" typedef int DataType; #include "LinStack.h" void main() { int i, d; LSNode *myLStack; StackInitiate(&myLStack); for (i = 0; i < 10; i++) { StackPush(myLStack, i+1); } StackTop(myLStack, &d); printf("栈顶元素为:%d /n", d); printf("链式栈堆的出栈顺序为:/n"); while(StackNotEmpty(myLStack)) { StackPop(myLStack, &d); printf("%d ", d); } }