/*
* 带头节点的栈:头结点的data属性用于记录栈中有几个元素
*/
#include <stdio.h>
#include <stdlib.h>
typedef int bool;
#define true 1
#define false 0
typedef struct node {
int data;
struct node *next;
} Node;
//
Node* Init() {
Node *node = (Node*) malloc(sizeof(Node));
if (!node)
return NULL;
node->data = 0;
node->next = NULL;
return node;
}
//入栈
bool PushTest(Node *node, int e) {
Node *p = (Node*) malloc(sizeof(Node));
if (!p)
return false;
p->data = e;
p->next = node->next;
node->next = p;
node->data++;
return true;
}
//出栈
int PopTest(Node *node) {
if (node->next == NULL)
return false;
Node *p = node->next;
node->next = p->next;
int e = p->data;
node->data--;
free(p);
return e;
}
//判空
bool IsEmpty(Node node) {
return node.next == NULL ? true : false;
}
//返回栈的长度
int StackLength(Node node) {
return node.data;
}
//打印栈的基本信息
void PrintStack(Node node) {
printf("%d\n", node.data);
printf("%d\n", IsEmpty(node));
Node *p = (&node)->next;
while (p) {
printf("%d\n", p->data);
p = p->next;
}
}
int main(void) {
Node *node = Init();
PrintStack(*node);
PushTest(node, 1);
PushTest(node, 2);
PushTest(node, 3);
PrintStack(*node);
PopTest(node);
PrintStack(*node);
return 0;
}
带头结点