define MAXSIZE 100
#include<stdio.h>
#include <cstdlib>
typedef struct {
int data;
char x;
}Qlemtype;
typedef struct Qnode{
Qlemtype data;
struct Qnode* next;
}Qnode,*Queueptr;
typedef struct {
Queueptr front;
Queueptr rear;
}LinkQueue;//联想单链表可知,这个地方相当于一个大指针,
//如果要继续定义一个指针指向链表某节点的话,还是要定义成Queueptr的。
//这个相当于对头尾指针的封装。
//或者理解,原来链表的指针都是S,L什么的,这里链表的指针叫做Q.rear/Q.front;
void InitLink(LinkQueue & Q) {
Q.front = Q.rear = (Queueptr)malloc(MAXSIZE * sizeof(Qlemtype));
if (Q.front == NULL)
{
printf("分配内存失败");
exit(-1); //如果为空,直接退出.
}
Q.front->next= Q.rear->next=NULL;//此处警告取消对指针的NULL引用,只要加上前面的if判空就行
}
//销毁
void Destry(LinkQueue& Q) {
while (Q.front) {
Queueptr p = Q.front->next;
free(Q.front);
Q.front = p;
}
}
void Insert(LinkQueue& Q, int n) {
Queueptr p;
for (int i = 0; i < n; i++) {
p = new Qnode;
p->next = NULL;
printf("please input the %d number:\n", i + 1);
scanf_s("%d", &(Q.rear->data.data));
Q.rear->next = p;
Q.rear=p;//这里不能写成什么Q.rear->next++, 可以写成Q.rear=Q.rear->next
}
}
void tarverseQueue(LinkQueue Q){
Queueptr cur = Q.front; // 当前指针
printf("the current queue is:\n");
while (cur!= Q.rear) // 直到cur指向了队尾元素的下一个位置,即Q.rear,结束循环
{
printf("%d ", cur->data.data);
cur=cur->next; // 当前指针向后推移
}
printf("\n");
}
void DeleteQueue(LinkQueue& Q,int n) {
int x;
printf("please input the quantity that you want to delete:\n");
scanf_s("%d", &x);
for (int i = 0; i < x; i++) {
if (x > n)
printf("the quantity is not correct!\n");
Q.front = Q.front->next;
}
}
void HeadNodePrintf(LinkQueue &Q) {
printf("the head element is :\n");
printf("%d", Q.front->data.data);
}
int main() {
printf("input your queue length:\n");
int x;
LinkQueue Q;
scanf_s("%d", &x);
InitLink(Q);
Insert(Q, x);
tarverseQueue(Q);
DeleteQueue(Q,x);
tarverseQueue(Q);
HeadNodePrintf(Q);
}
数据结构笔记5——链队
于 2024-05-24 17:23:37 首次发布