下面是源代码:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct QNode
{
ElemType data;
QNode* next;
};
struct Queue
{
QNode* rear;
QNode* front;
};
Queue* create()
{
QNode* q;
Queue* Q;
q=new QNode;
q->next=NULL;
Q->front=Q->rear=q;
return Q;
}
void EnQueue(Queue* Q,ElemType e)
{
QNode* N;
N=new QNode;
N->next=NULL;
N->data=e;
Q->rear->next=N;
Q->rear=N;
}
void DelQueue(Queue* Q)
{
QNode* N;
N=Q->front->next;
Q->front->next=N->next;
free(N);
}
void TraveQueue(Queue* Q)
{
while(Q->front->next!=NULL){
printf("%d",Q->front->next->data);
Q->front->next=Q->front->next->next;
}
}
int main()
{
Queue* Q;
Q=create();
EnQueue(Q,5);
EnQueue(Q,7);
EnQueue(Q,9);
TraveQueue(Q);
DelQueue(Q);
TraveQueue(Q);
}
单步调试的时候,无法删除元素,问题出在DelQueue函数里面,也就是Q->front->next=N->next求大神给予指导;
两个问题:
1.create函数里Q也需要分配空间,需要new
2.DelQueue函数里应该用delete,而不是free
3.你的TraveQueue函数,遍历的时候应该弄一个临时变量来遍历才行(你就是这里出错的!!!)
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct QNode
{
ElemType data;
QNode* next;
};
struct Queue
{
QNode* rear;
QNode* front;
};
Queue* create()
{
QNode* q;
Queue* Q = new Queue;
q = new QNode;
q->next = NULL;
Q->front = Q->rear = q;
return Q;
}
void EnQueue(Queue* Q, ElemType e)
{
QNode* N;
N = new QNode;
N->next = NULL;
N->data = e;
Q->rear->next = N;
Q->rear = N;
}
void DelQueue(Queue* Q)
{
QNode* N;
N = Q->front->next;
Q->front->next = N->next;
free(N);
}
void TraveQueue(Queue* Q)
{
QNode *temp = Q->front->next;
while (temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
Queue* Q;
Q = create();
EnQueue(Q, 5);
EnQueue(Q, 7);
EnQueue(Q, 9);
TraveQueue(Q);
DelQueue(Q);
TraveQueue(Q);
}
free(N);和malloc配对,new和delete配对,你的create用了q=new QNode;