头文件lkstack.h: #ifndef LKSTACK_H_ #define LKSTACK_H_ #define OK 1 #define ERROR -1 typedef char ElemType; typedef struct stacknode { ElemType data; struct stacknode *next; } lkstack; #define NODESZ sizeof(struct stacknode) lkstack *Init(lkstack *s); lkstack *Push(lkstack *s, const ElemType e); lkstack *Pop(lkstack *s); ElemType GetTop(const lkstack *s); int StackLength(const lkstack *s); int StackEmpty(const lkstack *s); int PrintStack(const lkstack *s); #endif /* LKSTACK_H_ */ lkstack.c: #include <stdio.h> #include <stdlib.h> #include "lkstack.h" lkstack *Init(lkstack *s) { s = (lkstack *) malloc(NODESZ); s->next = NULL; return s; } lkstack *Push(lkstack *s, const ElemType e) { if (NULL == s) { printf("ERROR: The stack is NULL!/n"); return NULL; } lkstack *p = (lkstack *) malloc(NODESZ); p->data = e; p->next = s->next; s->next = p; return s; } lkstack *Pop(lkstack *s) { if (s->next == NULL) { printf("ERROR: The stack is empty!/n"); return s; } lkstack *q = s->next; s->next = q->next; free(q); return s; } ElemType GetTop(const lkstack *s) { if (NULL == s->next) { printf("ERROR: The stack is empty!/n"); return '/0'; } return (s->next->data); } int StackLength(const lkstack *s) { if (NULL == s) { printf("ERROR: The stack is NULL!/n"); return ERROR; } int j = 0; lkstack *p = s; while (p->next != NULL) { p = p->next; j++; } return j; } int StackEmpty(const lkstack *s) { if (NULL == s) { printf("ERROR: The stack is NULL!/n"); return ERROR; } return (NULL == s->next); } int PrintStack(const lkstack *s) { if (NULL == s) { printf("ERROR: The stack is NULL!/n"); return ERROR; } printf("==============/n"); lkstack *p = s->next; while (p != NULL) { printf("%c", p->data); p = p->next; } printf("/n"); printf("==============/n"); } main函数LinkStack.c: #include <stdio.h> #include <stdlib.h> #include "lkstack.h" int main(void) { lkstack *s = NULL; s = Init(s); printf("Empty stack's length is:%d/n", StackLength(s)); s = Push(s, 'o'); s = Push(s, 'l'); s = Push(s, 'l'); s = Push(s, 'e'); s = Push(s, 'H'); PrintStack(s); printf("Stack's length is:%d/n", StackLength(s)); s = Pop(s); s = Pop(s); s = Pop(s); printf("Stack's top is:%c/n", GetTop(s)); s = Pop(s); s = Pop(s); s = Pop(s); s = Push(s, '1'); PrintStack(s); return EXIT_SUCCESS; }