队列(链表实现)

1.思路
定义结构体node表示链表里的节点,结构体linklist表示链表,选用两个首尾指针进行基本操作。

2.代码

#include<iostream>
using namespace std;

struct node {
    int value;
    node *next;
};

struct linklist { //带头尾指针的链表
    node* head;
    node* tail;
};

void Create(linklist* list) {
    if (list == NULL) {
        cout << "queue failed" << endl;
        return;
    }
    node* tmp = (node*)malloc(sizeof(node));
    tmp->next = NULL;
    tmp->value = 0;
    list->head = tmp;
    list->tail = tmp;
    return;
}

void EnQueue(linklist* list, int n) {
    node* tmp = (node*)malloc(sizeof(node));
    tmp->value = n;
    tmp->next = NULL;

    list->tail->next = tmp;
    list->tail = tmp;
}

int DeQueue(linklist* list) {
    if (list == NULL) {
        cout << "queue failed " << endl;
        return 0;
    }
    if(list->head == list->tail) {
        cout << "list empty!" << endl;
        return 0;
    }
    node* tmp = list->head->next;
    list->head->next = tmp->next;
    //若队内只要一个元素,则出队后要修改队尾指针
    if(tmp == list->tail) {
        list->tail = list->head;
    }
    int res = tmp->value;
    free(tmp);
    tmp = NULL;
    return res;
}

bool IsEmpty(linklist* list) {
    if (list == NULL) {
        cout << "queue failed" << endl;
        return false;
    }
    return list->head == list->tail;
}

void DestroyQueue(linklist* list) {
    while(list->head != NULL) {
        list->tail = list->head->next;
        free(list->head);
        list->head = list->tail;
    }
}

int main() {
    linklist *list = (linklist*)malloc(sizeof(linklist));
    Create(list);
    EnQueue(list, 1);
    EnQueue(list, 5);
    EnQueue(list, 3);

    cout << DeQueue(list) << endl;
    cout << DeQueue(list) << endl;

    EnQueue(list, 9);

    cout << DeQueue(list) << endl;

    cout <<"is empty?" << IsEmpty(list) << endl;

    cout << DeQueue(list) << endl;

    cout <<"is empty?" << IsEmpty(list) << endl;

    DestroyQueue(list);
    free(list);
    list = NULL;

    cout << DeQueue(list) << endl;
    return 0;
}

3.运行结果
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值