链式队列实现

#include  
#include  
#include  
#include  
#define VARTYPE char //默认存放char类型  
  
  
using namespace std;  
  
  
  
  
struct myNode;  
struct myQueue;  
typedef struct myNode Node;  
typedef Node* List;  
typedef Node* PtrToNode;  
typedef myQueue _Queue;  
  
  
struct myNode  
{  
    VARTYPE data;  
    PtrToNode next;  
};  
  
  
struct myQueue  
{  
    PtrToNode _rear;  
    PtrToNode _front;  
};  
  
  
void _push(_Queue* Q,VARTYPE x)  
{  
    PtrToNode tmp = (PtrToNode)malloc(sizeof(Node));  
    tmp->data = x;  
    tmp->next = NULL;  
    if(Q->_front == NULL)  
        Q->_front = tmp;  
    else  
        Q->_rear->next = tmp;  
    Q->_rear = tmp;  
}  
  
  
void _pop(_Queue *Q)  
{  
    PtrToNode pnode = Q->_front;  
    if(pnode!=NULL&&pnode->next!=NULL)  
    {  
        Q->_front = pnode->next;  
        free(pnode);  
    }  
    else if(pnode!=NULL&&pnode->next==NULL)  
    {  
        Q->_front = NULL;  
        Q->_rear = NULL;  
        free(pnode);  
    }  
}  
  
  
int _isempty(_Queue *Q)  
{  
    return Q->_front == NULL;  
}  
  
  
void _delstack(_Queue* &Q)  
{  
    PtrToNode tmp = Q->_front;  
    while(tmp!=NULL)  
    {  
        Q->_front = Q->_front->next;  
        free(tmp);  
        tmp = Q->_front;  
    }  
    Q->_rear = NULL;  
    Q = NULL;  
}  
  
  
VARTYPE _top(_Queue *Q)  
{  
    return Q->_front->data;  
}  
  
  
_Queue* create(_Queue* &Q)  
{  
    Q = (_Queue *)malloc(sizeof(_Queue));  
    if(Q==NULL)  
    {  
        perror("malloc failed");  
        return NULL;  
    }  
    else  
    {  
        Q->_front = NULL;  
        Q->_rear = NULL;  
        return Q;  
    }  
}  
  
  
int main()  
{  
    _Queue *Q = create(Q);  
    _push(Q,'a');  
    printf("%c ",_top(Q));  
    _push(Q,'b');  
    printf("%c ",_top(Q));  
    _push(Q,'c');  
    printf("%c ",_top(Q));  
    _push(Q,'d');  
    printf("%c ",_top(Q));  
    _delstack(Q);  
    return 0;  
}  

你可能感兴趣的:(链式队列实现)