| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
#include<iostream> 
#include"stdio.h" 
using namespace std; 
typedef int DATA; 
struct NodeType { 
    int data; 
    NodeType* next; 
}; 
class LinkRear { 
private: 
    NodeType* Head; 
    int len; 
public: 
    LinkRear(); //构造 
        ~LinkRear();   //析构 
    void input(int x);//入队 
    void output();    //出队 
    void print();      //打印队; 
    int getLen();     //获取队中元素个数 
}; 
LinkRear::LinkRear() {     //创建空链表 
    Head = new NodeType; 
    Head->next = NULL; 
    Head->data = 0; 
    len = 0; 
} 
LinkRear::~LinkRear() { 
    NodeType* p = Head->next;   //使p指向第一个节点 
    while (p != NULL) { 
        Head->next = p->next; 
        delete p; 
        p = Head->next; 
    } 
    delete Head; //最后将头节点也删除 
    len = 0; 
    cout<< "队列被清空!" <<endl; 
} 
void LinkRear::output() { 
    NodeType* p = Head->next;  //使p指向第一个节点 
    if (p != NULL) { 
        Head->next = p->next;  //使头节点指向p的下一个节点 
        cout << p->data << "出队" << endl; 
        delete p; 
    } 
    len--; 
} 
void LinkRear::input(int x) {   //入队 
    NodeType* p, * q; 
    q = Head; 
    while (q->next)q = q->next; 
    p = new NodeType; 
    p->data = x; 
    p->next = NULL; 
    q->next = p;   //插在表尾 
    len++; 
    cout << x << "入队" << endl; 
} 
void LinkRear::print() { 
    NodeType* p; 
    p = Head->next; 
    cout<< "队列中的元素为:"<< endl; 
    while (p != NULL) { 
        printf("%5d", p->data); 
        p = p->next; 
    } 
    cout << endl; 
} 
int LinkRear::getLen() { 
    return len; 
} 
void main() 
{ 
    LinkRear r1; 
    int data[] = { 23,45,3,7,6,945 }; 
    //显示菜单 
    cout << "==============" << endl; 
    cout << "1:入队" << endl; 
    cout << "2:出队" << endl; 
    cout << "3:打印队" << endl; 
    cout << "其他:退出" << endl; 
    cout << "==============" << endl; 
    int i = 1, j, op, size; 
    while (i == 1) { 
        cout << "请选择操作代码:"; 
        cin >> op; 
        switch (op) { 
        case1: 
            cout << "************入队操作*******" << endl; 
            size = sizeof(data) / sizeof(data[0]); 
            for (j = 0; j < size; j++) { 
                r1.input(data[j]); 
            } 
            break; 
        case2: 
            cout << "************出栈操作*******" << endl; 
            size = r1.getLen(); 
            for (j = 0; j < size; j++) { 
                r1.output(); 
            } 
            break; 
        case3:r1.print(); 
            cout << "队中元素个数" << r1.getLen() << endl; 
            break; 
        default:i = 0; 
        } 
    } 
} 
执行入队操作但结果显示队列被清空。
总共就一个错误,是case 1:不是case1:! 
你写错了,导致直接执行default后的语句,导致程序结束,r1销毁,调用析构函数,输出队列清空 
 
 
 |   
 
 
 
 |