队列 数据结构作业(二)

无聊的作业,既然花时间写了下,就随便贴下。。。
最简单的实现。。。

/** 样例输入输出: 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 2 队列已空,无法pop 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 1 input (type) a,a==-1 to end 23 input (type) a,a==-1 to end 345 input (type) a,a==-1 to end 56 input (type) a,a==-1 to end 34 input (type) a,a==-1 to end 45 input (type) a,a==-1 to end -1 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 2 pop(23) 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 2 pop(345) 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 3 traverse: 56 34 45 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 4 free: 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 5 rebuild: 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 1 input (type) a,a==-1 to end 23 input (type) a,a==-1 to end -1 输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束 -1 */

#include<iostream>
#include<cstdlib>
using namespace std;
typedef int type;

struct Queue
{
    type data;
    Queue *next;
};

Queue *head;   //头节点
Queue *cur;    //添加时移动
void Init()
{
    head=(Queue *)malloc(sizeof(Queue));
    cur=head;
    cur->next=NULL;
}

void push(type a)
{
    cout<<"input (type) a,a==-1 to end"<<endl;
    Queue *add;    //加的节点
    add=(Queue *)malloc(sizeof(Queue));
    add->data=a;
    cur->next=add;
    cur=add;
    cur->next=NULL;
}

void pop()
{
    if(head->next!=NULL)
    {
        cout<<"pop("<<head->next->data<<")"<<endl;
        head->next=head->next->next;
    }
    else
        cout<<"队列已空,无法pop"<<endl;
}

void traverse()
{
    cout<<"traverse:"<<endl;
    Queue *p=head;
    while(p->next!=NULL)
    {
        p=p->next;
        cout<<p->data<<" "<<endl;
    }
}

void free_queue()
{
    Queue *p;
    while(head!=NULL)
    {
        p=head;
        head=head->next;
        free(p);
    }
}

int main()
{
    cout<<"输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束"<<endl;
    int a;
    type b;
    Init();
    while(cin>>a&&a!=-1)
    {
        switch(a)
        {
            case 1:{cout<<"input (type) a,a==-1 to end"<<endl;while(cin>>b&&b!=-1){push(b);};break;};
            case 2:{pop();break;};
            case 3:{traverse();break;};
            case 4:{cout<<"free:"<<endl;free_queue();break;};
            case 5:{cout<<"rebuild:"<<endl;Init();break;}
            default:cout<<"please input 1 or 2 or 3 or -1"<<endl;
        }
        cout<<"输入:1.push 2.pop 3.traverse 4.free 5.rebuild -1结束"<<endl;
    }
    free_queue();
    return 0;
}

你可能感兴趣的:(数据结构,作业)