Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct Node {
- int data;
- struct Node* nxt;
- } Node;
- Node* newNode(int data, Node *nxt) {
- Node* node = (Node*)malloc(sizeof(Node));
- if (node == NULL) {
- perror("");
- exit(1);
- }
- node->data = data;
- node->nxt = nxt;
- return node;
- }
- typedef struct {
- Node* first;
- Node* last;
- } PQueue;
- int extract(PQueue pq) {
- if (pq.last == NULL) {
- perror("extract error");
- exit(1);
- }
- return pq.last->data;
- }
- void insert(PQueue *pq, int data) {
- if (pq->first == NULL) {
- pq->first = pq->last = newNode(data, NULL);
- return;
- }
- if (pq->first->data > data) {
- pq->first = newNode(data, pq->first);
- return;
- }
- Node* aux = pq->first;
- while (aux->nxt != NULL) {
- if (aux->data < data && data < aux->nxt->data) {
- aux->nxt = newNode(data, aux->nxt);
- return;
- }
- aux = aux->nxt;
- }
- pq->last->nxt = newNode(data, NULL);
- }
- void pop(PQueue *pq) {
- Node* aux = pq->first;
- while (aux->nxt != pq->last) {
- aux = aux->nxt;
- }
- free(pq->last);
- pq->last = aux;
- }
- void display(const PQueue *const pq) {
- for (Node* node = pq->first; node != NULL; node = node->nxt) {
- printf("%d ", node->data);
- }
- puts("");
- }
- void initPq(PQueue* pq) {
- pq->first = pq->last = NULL;
- }
- void freePQ(PQueue* pq) {
- Node* curr = pq->first;
- Node* nxt = NULL;
- while (curr) {
- nxt = curr->nxt;
- free(curr);
- curr = nxt;
- }
- }
- int main(void) {
- PQueue pq;
- initPq(&pq);
- insert(&pq, 12);
- insert(&pq, 4);
- insert(&pq, 1);
- insert(&pq, 3);
- insert(&pq, 5);
- insert(&pq, 45);
- insert(&pq, 40);
- display(&pq);
- freePQ(&pq);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement