源码
#include <stdio.h>
#include <stdlib.h>
typedef int E;
struct LNode {
E element;
struct LNode * next;
};
typedef struct LNode * Node;
void initStack(Node head) {
head->next = NULL;
}
_Bool pushStack(Node head, E element) {
Node node = malloc(sizeof(struct LNode));
if (node == NULL) return 0;
node->element = element;
node->next = head->next;
head->next = node;
return 1;
}
E popStack(Node head) {
Node tem = head->next;
E e = tem->element;
head->next = head->next->next;
free(tem);
return e;
}
_Bool isEmpty(Node head) {
return head->next == NULL;
}
void printStack(Node head) {
head = head->next;
while (head) {
printf("%d ", head->element);
head = head->next;
}
printf("| ");
printf("\n");
}
int main(void) {
struct LNode head;
initStack(&head);
for (int i = 0; i < 10; ++i) {
pushStack(&head, i + 1);
}
printStack(&head);
while (!isEmpty(&head)) {
printf("%d ", popStack(&head));
}
}