It's easy to put back what you've written.
We used to build a queue. The interface was not very friendly at first. We then optimized it.
Queue ABC; // declaring the queue structure body // Create queue abc.push (int num); // Press in int abc = abc.pop (); // Popup
This is roughly the case. But we found that this queue has a very obvious flaw. That is, you can only push into the variable of type int, if we want to press in other types. Even custom types. So we have to make a drastic change to this queue program. Almost all the code is changed, But the logic of the code is exactly the same, let a person "catch the urgency", not reconciled, the logic of the same code, each change type, we need to modify the majority of the code to use, such a program is what we do not want. So we need a generic queue with the goal of: 1. We don't need to modify the code of the queue. 2. It can push into any type if in C + +, there are template classes that can easily solve this problem, but in C we have to think of a clever way to accomplish this task. First, we only consider the queue, and its data structure is this:
struct _node{ struct _queue * prev; struct _queue * next;} Node;typedef Node// its pointer type
Then there is the behavior of it:
Node_pion Node_push (node_pion Tail, node_pion node)//give me a tail pointer, a knot.{ if(!node)returnNULL; if(tail) tail-next =node; Node->prev =tail; Tail=node; returntail;} Node_pion Node_pop (node_pion head)//give me a head pointer.{ if(head-next) Head->next->prev =NULL; Head= head->Next; returnHead; }
As seen from the above, there is not much difference from yesterday. Here's the key: Then we encapsulate this queue:
typedefstruct_queue{node_pion HEAD;//It's headNode_pion TAIL;//the tail of it}queue;typedef Queue*queue_pion;//It's behavior//Constructionqueue_pion ctreate_queue (queue_pion Queue) {if(!queue) Queue= (queue_pion)malloc(sizeof(_queue)); Queue->head =NULL; Queue->tail =NULL;returnqueue;}//Destructionvoiddelete_queue (queue_pion queue) { Free(queue);}//Press invoidPush (Queue_pion Queue,void*node) {if((!queue->head) && (!queue->tail))//if a tail is equal to null. Invalid queueQueue->tail = Queue->head = Node_push (Queue->tail, (node_pion) node);//re-establish the queue ElseQueue->tail = Node_push (Queue->tail, (node_pion) node);//give me a tail pointer, a knot.}//Popupvoid*pop (queue_pion Queue) {node_pion P= queue->HEAD; Queue->head = Node_pop (queue->HEAD); return(void*) p;}
So, we're going to be more fun when we use it. For example, we have a custom type
struct abc{ int num; int Val;};
Then, in the code, we construct a queue:
Queue *abc =struct _abc{ node node; // our first element in this custom structure, plus an element of our node structure. int num; int Val;} *ABC; It's a good name.
ABC p= (ABC) malloc (sizeof (_ABC)); Apply for a new object push (BGD,P); So that it can be pressed into the queue of pop (BGD); So you can pop it up, it's easier.
C-language Simple queue