我对队列的学习
来源:互联网 发布:网络写作和传统写作 编辑:程序博客网 时间:2024/05/22 10:36
这篇文章主要是体现我对队列和链表的理解
根据我的理解,队列是一个概念,一种对数据管理的手段------先入先出。它的操作单位可以是数组,也可以是链表。而我们的链表就是一个线性表而已,你可以随便插在哪个结点,随便删除哪个结点,但是将它加入队列后就必须按照队列的方法来实现数据的管理。
我还是用代码来说明吧。
1.首先创建链表和队列的结构体
typedef struct link{ int data; struct link *next;}node;typedef struct Queue{ node *front,*rear;}queue;这里我想说一下的就是队列中的front和rear指针个人理解就是一个下标而已,让我们能够区别一下队首和队尾。
2.链表和队列的函数构造
queue *creat_queue(){ queue *q=(queue *)malloc(sizeof(queue)); q->front=NULL; q->rear=NULL; return q;}
node * creat_link(int n){ node *new,*pre,*head; int i=0; new=NULL; head=(node *)malloc(sizeof(node)); head->next=NULL; pre=head; for(;i<n;i++) { new=(node*)malloc(sizeof(node)); printf("input the data\n"); scanf("%d",&new->data); pre->next=new; pre=new; } pre->next=NULL; return head;}我的思路是首先创建一个单项链表,然后把它加入到队列中去
3.队列的入队
void insert_link_to_queue(queue*q,node * head){ node *newp; newp=head->next; while(newp) { if(q->rear==NULL) { q->front=q->rear=newp; } else { q->rear->next=newp; q->rear=newp; } newp=newp->next; }}
这里主要需要注意的是判断条件,如果是一个空队列就把front,rear两个下标都给第一个数据,然后再插的时候就把rear下标往后移一个,直到我们所有链表的数据对入队
4.队列的出队
void delete_queue(queue * q){ node *pnode=NULL; pnode=q->front; if(pnode==NULL) { printf("empty queue!\n"); } else { q->front=q->front->next; if(q->front==NULL) { q->rear=NULL; } free(pnode); }}
这里我们使用到了一个node指针,因为队列是先入先出,所有带有front这个下标的数据就先出去,出去后front下标就后一位,第二个数就成队首了,我们只需要将node指针指向它即可然后free掉我们的结点,就完成了我们的出队操作。
5.获得队列的长度
int getlength(queue *q){ int nlen=0; node *pnode=q->front; if(pnode!=NULL) { nlen=1; } while(pnode!=q->rear) { pnode=pnode->next; nlen++; } return nlen;}
/*注意在代码中,循环结束的条件是"pnode != q->rear",而不应该与NULL做比较,即"pnode != NULL",这是因为队尾有可能指向的不是一个链表的末节点,只是这里我们把整个链表都传进去了*/也可以while(pnode!=NULL) 然后把上面的改成if(pnode==NULL) nlen=0;
6.队列数据显示
void printqueue(queue * q){ node * pnode=q->front; if(pnode==NULL) { printf("empty queue!\n"); return ; } printf("data:"); while(pnode!=q->rear) { printf("%d,",pnode->data); pnode=pnode->next; } printf("%d",pnode->data);}
这里的循环条件也是和上面一样的道理,只是我这里把整个链表放进去了,所以要改的话也可以while(pnode!=NULL) 再注释到最后一个数据的输出即可。
然后就是我的main函数
void main(){ int nlen=0; int i=0; node * head; printf("input the number of the data\n"); scanf("%d",&i); head=creat_link(i); queue *hp=creat_queue(); insert_link_to_queue(hp,head); nlen=getlength(hp); printf("nlen=%d\n",nlen); printqueue(hp); delete_queue(hp); delete_queue(hp); nlen=getlength(hp); printf("\nneln=%d\n",nlen); printqueue(hp); printf("\n");}
实验效果图:
0 0
- 我对队列的学习
- 我对消息队列的理解
- 我对栈的学习
- 我 对 数论的学习
- 谈谈我对数据结构中栈和队列的理解
- 我对学习数据结构的一些看法!
- 谈我对计算机学习的理解
- 我对学习数学的感觉
- 我对自己学习的思考
- 我对计算机体系结构学习的理解
- 浅谈我对机器学习的理解
- 我对学习的一点看法
- 浅谈我对机器学习的理解
- 浅谈我对机器学习的理解
- 我对Linux 权限管理的学习
- 我对单向链表的学习
- 我对UiAutomator学习的一些总结
- 我对学习的一些思考
- 第3周 项目1-顺序表的基本运算
- Linux下vsftp搭建
- 第三周—项目1 顺序表的基本运算
- 个人笔记:JNI---1
- 第2周 项目2 程序的多文件组织
- 我对队列的学习
- xib与storyBoard中控件属性设置问题
- SQL server 学习(1)--SQL常用语法命令整理
- 数据结构,算法与应用(1)
- 如何写文件到/data/data/packagename/files中
- 开发的第一个iOS app
- nginx 内置变量大全
- jvm参数设置心得
- ffmpeg 读取MPEG-TS流,切割TS流支持【HLS协议】