赞
踩
- /*基本队列的实现*/
- #include<stdio.h>
- #include<stdlib.h>
- #include<assert.h>
- #include<malloc.h>
- #include<stdbool.h>
-
- //通过链表实现就要定义一个链表
- typedef struct ListNode
- {
- struct ListNode* next;
- int val;
- }ListNode;
- //定义两个节点指针 也可以解决使用二级指针的方法
- typedef struct queue
- {
- ListNode* head;
- ListNode* tail;
- }queue;
-
- //接口
- //初始化栈接口
- void QueueInit(queue*q)
- {
- q->head = q->tail = NULL;
- }
- //销毁栈接口
- void QueueDestory(queue* q)
- {
- assert(q);
- ListNode* cur = q->head;
- while (cur)
- {
- ListNode*next= cur->next;
- free(cur);
- cur = next;
- }
- q->head = q->tail = NULL;
-
-
- }
- //队尾进接口
- void QueuePush( queue*q,int val)
- {
- assert(q);
- ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
- if (newnode == NULL)
- {
- printf("创建节点失败!\n");
- exit(-1);
- }
- else
- {
- newnode->next = NULL;
- newnode->val = val;
- }
-
- if (q->tail==NULL)
- {
- q->tail = q->head = newnode;
- }
- else
- {
- q->tail->next = newnode;
- q->tail = newnode;
- }
- }
- //队头出接口
- void QueuePop(queue* q)
- {
- assert(q);
- assert(q->head);
- //极端情况 就是队列只有一个节点的情况 此时你的tail的空间已经被释放了但是你的tail还是指向一块地址的 所有tail会形成一个野指针
- //单独判断
- if (q->head->next==NULL)
- {
- free(q->head);
- q->head = q->tail = NULL;
- }
- else
- {
- ListNode* tmp = q->head->next;
- free(q->head);
- q->head = tmp;
- }
-
- }
-
- bool QueueEmpty(queue* q);
- //返回队头的接口
- int QueueFront(queue* q)
- {
- assert(q);
- if (!QueueEmpty(q))
- {
- return q->head->val;
- }
- else
- {
- return NULL;
- }
- }
-
- //返回队尾接口
- int QueueBack(queue* q)
- {
- assert(q);
- assert(q->head);
- return q->tail->val;
- }
- bool QueueEmpty(queue* q)
- {
- assert(q);
- //为空就是真
- return q->head == NULL;
- }
-
- int main()
- {
-
- queue q;
- QueueInit(&q);
-
- QueuePush(&q, 1);
- QueuePush(&q, 2);
- QueuePush(&q, 3);
- QueuePush(&q, 4);
- while (!QueueEmpty(&q))
- {
- printf("%d ", QueueFront(&q));
- QueuePop(&q);
- }
- printf("\n");
- int ret = QueueFront(&q);
- printf("%d ", ret);
- return 0;
- }

赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。