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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是链表实现C语言代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表结点 typedef struct Node{ int data; struct Node* next; } Node; // 定义结构体 typedef struct Stack{ Node* top; int size; } Stack; // 初始化 void initStack(Stack* s){ s->top = NULL; s->size = 0; } // 判断是否为空 int isEmpty(Stack* s){ return s->size == 0; } // 入操作 void push(Stack* s, int data){ Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = s->top; s->top = newNode; s->size++; } // 出操作 int pop(Stack* s){ if(isEmpty(s)){ printf("为空,无法出"); return -1; } int data = s->top->data; Node* temp = s->top; s->top = s->top->next; free(temp); s->size--; return data; } // 获取顶元素 int peek(Stack* s){ if(isEmpty(s)){ printf("为空,无法获取顶元素"); return -1; } return s->top->data; } int main(){ Stack s; initStack(&s); push(&s, 1); push(&s, 2); push(&s, 3); printf("顶元素为:%d\n", peek(&s)); printf("出元素为:%d\n", pop(&s)); printf("出元素为:%d\n", pop(&s)); printf("出元素为:%d\n", pop(&s)); printf("是否为空:%d\n", isEmpty(&s)); return 0; } ``` 在上面的代码中,我们使用了链表实现。在的初始化函数中,我们将顶指针置为 NULL,并将的大小设为 0。在入操作时,我们创建一个新的链表结点,将其插入到链表的头部,并将顶指针指向该结点。在出操作时,我们首先判断是否为空,如果为空则输出错误信息;否则,我们取出顶元素,并将顶指针指向下一个结点。在获取顶元素时,我们同样需要判断是否为空。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值