c - 栈,队列笔记

本文详细介绍了栈(后进先出LIFO)和队列的数据结构,包括它们的定义、C语言中结构体和函数的实现,以及初始化、入栈/入队、出栈/出队和打印操作。
摘要由CSDN通过智能技术生成

底部称为栈底,顶部称为栈顶,所有的操作只能在栈顶进行

栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构

struct listnode{

    int data;

    struct listnode *next;

};

typedef struct listnode* node;

 

void initstack(node head) {

    head->next = NULL;

    }

//入栈

bool pushstack(node head, int ele){

    node stack = malloc(sizeof(struct listnode));

    if(stack==NULL)

        return 0;

    stack->data = ele;

    stack->next = head->next;

    head->next = stack;

    return 1;

}

//出栈

int popstack(node head){

    int pop_data;

    node pop_stack = head->next;

    pop_data = pop_stack->data;

    head->next = head->next->next;

    free(pop_stack);

    return pop_data;

}

//打印

void printStack(node head){

    head = head->next;

    while(head != NULL){

        printf("&d", head->data);

        head = head->next;

    }

}

队列

队列中的元素只能从队尾进入,只能从队首出去.

对于初始化需要初始化两个类型,一个是初始化结点,一个是初始化队列。代码中的描述,初始化队列有些不同,当初始化队列的时候,需要将头尾两个结点指向的内容统统置为空。

Q->front == NULL 并且 Q->rear == NULL 时,链队列为空。

//节点初始化

struct queuenode{

    int data;

    struct queuenode *next;

};

typedef struct queuenode* queuenode_t;

//头尾

struct queue{

    queuenode_t rear;

    queuenode_t front;

};

//队列初始化

typedef struct queue* queue_t;

bool queue_init(queue_t Q)

{

    queuenode_t node = malloc(sizeof(struct queuenode));

    if(node == NULL)

        return 0;

    Q->rear = Q->front = node;

}

//入列

bool inqueue(queue_t Q, int data)

{

    queuenode_t node = malloc(sizeof(struct queuenode));

    node->data = data;

    node->next = Q->rear->next;

    Q->rear->next = node;

}

//出列

int outqueue(queue_t Q){

    int ele;

    queuenode_t node = Q->front->next;

    ele = node->data = Q->front->next->data;

    Q->front->next = Q->front->next->next;

    if (Q->rear == node)

        Q->rear = Q->front;

    free(node);

    return ele;

}

//打印

void printqueue(queue_t Q){

    queuenode_t node = Q->front->next;

    do

    {

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

        node = node->next;

    } while (node == Q->rear);

   

}

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YELL.DOLL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值