c语言栈链表详解,栈(c语言)链表实现

节点的结构

struct Node

{

int value;

struct Node* next;

};

typedef struct Node Node;

基本功能和操作演示

#include

#include

struct Stack

{

Node *node;

int size;

};

typedef struct Stack Stack;

// 建立一个节点

Node *createNode(int value)

{

Node *node = (Node *) malloc(sizeof(Node));

node->next = NULL;

node->value = value;

return node;

}

// 建立一个空栈

Stack *createStack()

{

Stack *stack = (Stack *) malloc(sizeof(Stack));

stack->node = NULL;

stack->size = 0;

return stack;

}

// 添加一个元素

void push(Stack *stack, Node *node)

{

node->next = stack->node;

stack->node = node;

stack->size++;

}

// 检测是否为空

int isEmpty(Stack *stack)

{

return stack->size <= 0 ? 1 : 0;

}

// 弹出一个元素

void pop(Stack *stack)

{

if (isEmpty(stack))

{

printf("this stack is empty!");

return;

}

Node *node = stack->node;

stack->node = stack->node->next;

stack->size--;

free(node);

}

// 获取栈顶元素

Node *top(Stack *stack)

{

if (isEmpty(stack))

{

printf("this stack is empty!");

return NULL;

}

return stack->node;

}

// 获取当前元素的个数

int size(Stack *stack)

{

return stack->size;

}

int main()

{

Stack *stack = createStack();

Node *node = createNode(10);

push(stack, node);

node = createNode(20);

push(stack, node);

printf("size = %d\n", size(stack));

while (!isEmpty(stack))

{

node = top(stack);

printf("%d ", node->value);

pop(stack);

}

printf("\n");

printf("size = %d\n", size(stack));

return 0;

}

来源:https://www.cnblogs.com/li1234567980/p/13406107.html

你可能感兴趣的:(c语言栈链表详解)