1.声明
此代码有参考小甲鱼的数据结构的算法,写出来怕自己忘记,不说了直接上代码吧!
#include<stdio.h>
#include<stdlib.h>
typedef struct Qnode
{
char data;
struct Qnode* next;
}Qnode,*QueuePrt;
typedef struct
{
Qnode *front;//队列头
Qnode * read;
}LinkQueue;
//初始化队列
int initQueue(LinkQueue* q)
{
q->front=q->read=(QueuePrt)malloc(sizeof(Qnode));
if (q->front==NULL)
{
return -1;
}
q->front->next = NULL;
return 1;
}
//进入队列
int Pust(LinkQueue *q,char s)
{
Qnode* p;
p = (QueuePrt)malloc(sizeof(Qnode));
if (p == NULL)
{
return 0;
}
p->data = s;
p->next = NULL;
q->read->next = p;
q->read = p;//p继承尾结点
return 1;
}
//出队列
int del(LinkQueue* q, char* e)
{
Qnode* p;
p = (Qnode*)malloc(sizeof(Qnode));
if (q->front == q->read)//当头尾相同时,没有元素了返回
{
return 0;
}
p = q->front->next;
*e = p->data;
q->front->next = p->next;
if (q->read == p)
{
q->read = q->front;//删除最后一个元素的时候
}
free(p); //释放掉然后重新获取新的地址
return 1;
}
//打印队列
void print(LinkQueue* q)
{
while (q->front != q->read)
{
q->front = q->front->next;
printf("%c ", q->front->data);
}
}
//销毁函数
int DeQueue(LinkQueue* q)
{
while (q->front)
{
q->read = q->front->next;
free(q->front);
q->front = q->read;
}
return 1;
}
int main()
{
char c,e;
LinkQueue q;//这里做了一下比较,用指针类型的不包含data和next的元素
LinkQueue* s;
initQueue(&q);
printf("请输入字符:");
scanf_s("%c",&c,1);
while (c != '\n')
{
Pust(&q, c);
scanf_s("%c", &c,1);
}
printf("\n");
printf("删除一个字符:");
del(&q, &e);
print(&q);
DeQueue(&q);
return 0;
}
2.总结
虽然代码不复杂,但是对于不太了解指针的我来说有点难受,看来我要多练习练习指针这一章。