CodeHighlight

2013年9月28日 星期六

[DS]Queue 實作 by C

這次像上篇一樣,不過改練習Queue的實作,
基本概念就是先進先出,是只做了enQueue、deQueue、listQueue三個

是說很久沒有寫了,在enQueue的地方還有點懷疑這樣寫到底正不正確XD


#include<stdio.h>
#include<stdlib.h>

typedef struct node{
        int data;
        struct node *next;
}NODE;

NODE* inQueue(NODE *top, int input){
        NODE *newNode;
        NODE *headPtr = top;
        newNode = (NODE*)malloc(sizeof(NODE));
        newNode->data = input;
        newNode->next = NULL;
        if(top == NULL){
                return newNode;
        }
        while(top->next != NULL){       //move to last
                top = top->next;
        }
        top->next = newNode;
        return headPtr;
}

NODE* deQueue(NODE *top){
        NODE *tmpNode = top;
        if(top == NULL){return top;}
        top = top->next;
        free(tmpNode);
        return top;
}

void listQueue(NODE* top){
        if(top == NULL){
                printf("EMPTY QUEUE\n");
                return;
        }
        while(top != NULL){
                printf("%d ", top->data);
                top = top->next;
        }
        printf("\n");
}

int main(){
        NODE *node;
        node = inQueue(node, 1);
        listQueue(node);
        node = inQueue(node, 2);
        listQueue(node);
        node = inQueue(node, 3);
        listQueue(node);
        node = deQueue(node);
        listQueue(node);
        node = deQueue(node);
        listQueue(node);
        node = deQueue(node);
        listQueue(node);
        node = deQueue(node);
        listQueue(node);
        node = inQueue(node, 1);
        node = inQueue(node, 2);
        node = inQueue(node, 3);
        node = inQueue(node, 4);
        node = inQueue(node, 5);
        listQueue(node);
        node = deQueue(node);
        node = deQueue(node);
        node = deQueue(node);
        listQueue(node);
        return 0;
}

沒有留言:

張貼留言