委实看不懂了,C++primer plus 12章队列模拟
实在看不懂了,C++primer plus 12章队列模拟
这个bool函数看不懂了,rear = add到底什么意思啊?上面已经rear->next = add了,让rear的next指针指向add,因此add变成最后一个节点,再用rear = add,不就又重复操作,且将rear->next = add 刚赋的值给覆盖了吗?
期待帮助,尽肯能通俗详细的教教我,谢了!
------解决方案--------------------
class Queue
{
private:
struct Node{Item item;struct Node * next;};
enum {Q_SIZE = 10};
Node * front; //前一个数据
Node * rear; //后一个数据
int items; //当前数据的数量
const int qsize; //最大的数量
public:
Queue(int qs):qsize(qs),front(NULL),rear(NULL),items(0)
{
//front = NULL;
//rear = NULL;
//items = 0;
}
~Queue();
bool isempty()const;
bool isfull()const;
int queuecount()const;
bool enqueue(const Item & item);//增至队尾
bool dequeue(Item & item);//队首删除
};
bool enqueue(const Item & item)
{
//满的就退出
if(this->isfull())
{
return false;
}
//空的队列就增加
Node *add = new Node;
if(add == NULL)
return false;//未申请到内存也退出
add->item = item; //add的item就是形参
add->next = NULL;//add结构的next成员指针设为null
items++;
if(front == NULL) //如果队列是空
front = add; //add就为第一个
else
rear->next = add; //否则,就将当前对象的rear指针指向add,
rear = add;
return true;
}
这个bool函数看不懂了,rear = add到底什么意思啊?上面已经rear->next = add了,让rear的next指针指向add,因此add变成最后一个节点,再用rear = add,不就又重复操作,且将rear->next = add 刚赋的值给覆盖了吗?
期待帮助,尽肯能通俗详细的教教我,谢了!
------解决方案--------------------
//不带表头结点的单向链表
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
#include <locale.h>
struct NODE {
int data;
struct NODE *next;
} *head,*p,*q,*s,*p1,*p2,*q1,**ta;
int i,k,n,t,m,v,N=10;
int main() {
setlocale(LC_ALL,"chs");
srand(time(NULL));
head=NULL;
printf("创建%d个节点的单链表:",N);//创建N个节点的单链表
p=head;
for (i=0;i<N;i++) {
q=(struct NODE *)malloc(sizeof(struct NODE));
if (NULL==q) exit(1);
q->data=rand()%100;//填写0..99的随机值
q->next=NULL;
if (NULL==p) {
head=q;
p=head;
} else {
p->next=q;
p=q;
}
}
//输出整个单链表
s=head;
while (1) {
if (NULL==s) {
printf("\n");
break;
}
printf("%02d->",s->data);
s=s->next;
}
k=3;
v=5;
printf("将值为%d的结点插入到单链表的第%d个结点前:",v,k);//将值为v的结点插入到单链表的第k个结点前
n=0;
p=head;
while (1) {
if (NULL==p) {
break;
}
n++;
if (k==1) {
q=(struct NODE *)malloc(sizeof(struct NODE));
if (NULL==q) exit(1);
q->data=5;
q->next=head;
head=q;
break;
} else {
if (k-1==n) {
q=(struct NODE *)malloc(sizeof(struct NODE));
if (NULL==q) exit(1);
q->data=5;