赞
踩
#include <stdlib.h> #include <stdbool.h> #include <stdio.h> //用链表实现队列 typedef int E; typedef struct node_s { E val; struct node_s* next; }Node; typedef struct queue_s { Node* head; Node* tail; }Queue; Queue* Queue_create() { return (Queue*)calloc(1, sizeof(Queue)); } void Queue_destory(Queue* q) { Node* curr = q->head; while (curr != NULL) { Node* next = curr->next; free(curr); curr = next; } free(q); } bool isEmpty(Queue* q) { return q->head == NULL; } void enqueque(Queue* q, E val) { Node* newNode = (Node *) malloc(sizeof(Node)); if (newNode == NULL) { printf("Error: malloc failed in enqueque.\n"); exit(1); } //初始化结点 newNode->val = val; newNode->next = NULL; if (q->tail == NULL) { //插入第一个结点 q->head = q->tail = newNode; } else { q->tail->next = newNode; q->tail = newNode; } } E dequeue(Queue* q) { if (isEmpty(q)) { printf("Errpr: queue is empty.\n"); exit(1); } Node* node = q->head; E removeValue = node->val; q->head = node->next; if (q->head == NULL) { q->tail = NULL; } free(node); return removeValue; } E peek(Queue* q) { if (isEmpty(q)) { printf("Error: queue is empty.\n"); exit(1); } return q->head->val; } int main(void) { Queue* q = Queue_create(); enqueque(q, 1); enqueque(q, 2); enqueque(q, 3); dequeue(q); peek(q); Queue_destory(q); return; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。