链队列的出队,需要注意一下,这里我在运行时遇到一些问题。
运行结果 源码#includeusing namespace std; typedef struct QNode { int data; QNode* next;// 指向下一个结点的指针 }Node, *Pointer; // 定义了一个可以指向这一变量的指针 typedef struct Queue//链队列 { Pointer front;// 链队列的头指针 Pointer tail;// 尾指针 }Que; void Init(Que& Q) { Node* head = new Node;// 指向头结点的指针 Q.front = Q.tail = head;// 队头队尾指向头结点 Q.front->next = NULL;// 链队列头指针指向空 } bool EnQueue(Que& Q, int e) { Node* p = new Node; p->data = e; //p->next = NULL;// 这句对运行没有影响 不过逻辑上需注意到它 Q.tail->next = p;//将新结点插入到队尾 Q.tail = p; return true; } bool OutQueue(Que& Q, int& e)// 队头元素出队 有点东西 { if (Q.front != Q.tail) { Node* q = Q.front->next;// 临时保存头结点的后一个结点 e = q->data; Q.front->next = q->next;// 不能写成q = q->next; 这修改的会是q if (Q.tail == q) Q.front = Q.tail; delete q; return true; } return false; } int GetFront(Que& Q) { if(Q.front != Q.tail) return Q.front->next->data;// 容易忘记Q.front指向的是头结点 说明还不够熟悉 } int main() { Que Q; Init(Q); int code; int e; do { printf("请输入 *** 作码 0-退出系统 1-入队 2-出队 3-取队头元素n"); cin >> code; switch (code) { case 1: cout << "请输入入队元素 输入-1退出操作n"; cin >> e; while (e != -1) { EnQueue(Q, e); cout << "元素" << e << "入队n"; cin >> e; } break; case 2: if (!OutQueue(Q, e)) { cout << "队为空n"; break; } cout << "元素" << e << "出队n"; break; case 3: cout << "队头元素为" << GetFront(Q) << "n"; break; } } while (code != 0); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)