Created
April 18, 2013 09:25
-
-
Save matteobertozzi/5411425 to your computer and use it in GitHub Desktop.
queue by type?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdint.h> | |
| #include <stdlib.h> | |
| #include <stdio.h> | |
| struct node { | |
| struct node *onext; | |
| struct node *cnext; | |
| int type; | |
| int value; | |
| }; | |
| struct queue { | |
| struct node *head; | |
| struct node *tail; | |
| }; | |
| static struct node *__node_alloc (int type, int value) { | |
| struct node *node; | |
| node = (struct node *) malloc(sizeof(struct node)); | |
| node->onext = NULL; | |
| node->cnext = NULL; | |
| node->type = type; | |
| node->value = value; | |
| return(node); | |
| } | |
| static void __push (struct queue *queue, struct node *node) { | |
| struct node *tail; | |
| node->onext = node; | |
| node->cnext = NULL; | |
| if ((tail = queue->tail) != NULL) { | |
| if (tail->type == node->type) { | |
| tail->onext->cnext = node; | |
| tail->onext = node; | |
| } else { | |
| tail->onext = node; | |
| queue->tail = node; | |
| } | |
| } else { | |
| queue->head = node; | |
| queue->tail = node; | |
| } | |
| } | |
| static struct node *__pop (struct queue *queue) { | |
| struct node *head; | |
| struct node *node; | |
| if ((head = queue->head) == NULL) | |
| return(NULL); | |
| if ((node = head->cnext) != NULL) { | |
| node->onext = head->onext; | |
| queue->head = node; | |
| } else if (head != head->onext) { | |
| queue->head = head->onext; | |
| } else { | |
| queue->head = NULL; | |
| queue->tail = NULL; | |
| } | |
| return(head); | |
| } | |
| static void __dump (struct queue *queue) { | |
| struct node *p; | |
| for (p = queue->head; p != NULL; p = p->onext) { | |
| struct node *q; | |
| printf("%d: ", p->type); | |
| for (q = p; q != NULL; q = q->cnext) { | |
| printf("%d -> ", q->value); | |
| } | |
| printf("X\n"); | |
| if (p == p->onext) | |
| break; | |
| } | |
| } | |
| int main (int argc, char **argv) { | |
| struct queue queue; | |
| struct node *node; | |
| queue.head = NULL; | |
| queue.tail = NULL; | |
| __push(&queue, __node_alloc(10, 0)); | |
| __push(&queue, __node_alloc(10, 1)); | |
| __push(&queue, __node_alloc(20, 1)); | |
| __push(&queue, __node_alloc(20, 2)); | |
| __push(&queue, __node_alloc(20, 3)); | |
| __push(&queue, __node_alloc(10, 4)); | |
| __push(&queue, __node_alloc(30, 5)); | |
| __dump(&queue); | |
| while ((node = __pop(&queue)) != NULL) { | |
| printf("POP %d %d\n", node->type, node->value); | |
| } | |
| return(0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment