用链表存放队列,书上是用的伪指针,比较关键的一点是队列头部到达块的上限时,继续压入元素,会导致伪指针指向块的起始位置,链表无需顾忌这个问题
#include <iostream> using namespace std; struct strqueue; typedef struct strqueue *StrQueue; StrQueue create_StrQueue(void);//creates a new StrQueue ,caller must call destroy_StrQueue) void destroy_StrQueue(StrQueue sq);//frees the memory occupied by StrQueue) void push_back(StrQueue sq, const char *str);//把str加在sq的最后) char *pop_front(StrQueue sq);//frees the node at the front of the sq and returns the string that was first in sq char *peek_front(StrQueue sq);//returns a the first item stored in sq) int get_length(StrQueue sq);//returns the number of items in the queue) //StrQueue.c typedef struct Node { char *data; Node *next; }node,*pnode;//元素节点 typedef struct { int length; pnode front; pnode rear; }_StrQueue,*pStrQueue;//队列 StrQueue create_StrQueue(void)//创建一个队列 { pStrQueue p=(pStrQueue)malloc(sizeof(_StrQueue)); memset(p,0,sizeof(_StrQueue)); return (StrQueue)p; } void destroy_StrQueue(StrQueue sq)//销毁一个队列 { pStrQueue Q=(_StrQueue*)sq; pnode temp; if(Q->front==NULL)return; while(Q->front!=NULL) { temp=Q->front->next; free((pnode)(Q->front)); Q->front=temp; } Q->length=0; } void push_back(StrQueue sq, const char *str)//从尾部压入一个元素 { pStrQueue Q=(_StrQueue*)sq; pnode q = pnode(malloc(sizeof(node))); q->data=(char *)malloc(strlen(str)); strcpy_s(q->data,sizeof(str),str); q->next=NULL; if(Q->rear==NULL){Q->rear=q;Q->front=Q->rear;return;} Q->rear->next=q; Q->rear=q; Q->length++; } char *pop_front(StrQueue sq)从头部弹出一个元素 { pStrQueue Q=(_StrQueue*)sq; pnode temp=NULL; char *p; if(Q->front==NULL)return "Empty Queue"; temp=Q->front->next; p=Q->front->data; free((pnode)Q->front); Q->front=temp; Q->length--; return p; } char *peek_front(StrQueue sq)//取头部元素 { pStrQueue Q=(_StrQueue*)sq; if(Q->front==NULL)return "Empty Queue"; return Q->front->data; } int get_length(StrQueue sq)//获取队列的长度 { return ((_StrQueue*)sq)->length; } int main() { StrQueue p=create_StrQueue(); push_back(p,"abc"); push_back(p,"a1c"); push_back(p,"a2c"); pop_front(p); cout<<peek_front(p)<<endl; destroy_StrQueue(p); system("pause"); return 0; }