用链表的形式好处就是没有空间不够用或者空间剩余太多的问题
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Line {
int data;//数据域
struct Line* next;//指针域
}Line;
Line* createLine()//创建队列(队头)
{
Line* front;
if ((front = (Line*)malloc(sizeof(Line))) == NULL)
{
printf("内存分配失败");
exit(1);//异常退出
}
front->next = NULL;
return front;
}
Line* createNode(int data)//创建结点
{
Line* newNode;
if ((newNode = (Line*)malloc(sizeof(Line))) == NULL)
{
printf("内存分配失败");
exit(1);//异常退出
}
newNode->data=data;
newNode->next = NULL;
return newNode;
}
void insertNodeByrear(Line* front,int data)//在队尾插入结点
{
Line* rear=front;
while (rear->next!=NULL)rear = rear->next;
Line* newNode = createNode(data);
rear->next = newNode;//rear=newNode;
}
void printLine(Line* front)//便历
{
Line* rear = front;
while (rear->next)rear = rear->next;
Line* pMove = front->next;
if (rear == front)
{
printf("队列为空");
return;
}
else
while (pMove)
{
printf("%d\t", pMove->data);
pMove=pMove->next;
}
printf("\n");
}
void deleteNodebyfront(Line* front)//从队头删除结点
{
Line* rear = front;
while (rear->next)rear = rear->next;
Line* pMove = front->next;
if (!pMove)
{
printf("队列已空,无法删除\n");
return;
}
else
{
if (pMove == rear)
{
front->next = NULL;
free(pMove);
}
else
{
front->next = pMove->next;
free(pMove);
}
}
}
int main()
{
Line* list = createLine();
int choice;
menu:
system("cls");
printf("1、在队尾插入结点\n");
printf("2、从队头删除结点\n");
printf("3、便历\n");
printf("4、退出\n");
printf("请输入选项:");
scanf_s("%d", &choice);
switch (choice)
{
case 1:
int data;
printf("请输入你要插入的数据");
scanf_s("%d", &data);
insertNodeByrear(list, data);
break;
case 2:
deleteNodebyfront(list);
printf("操作完成\n");
break;
case 3:
printLine(list);
break;
case 4:
exit(0);
default:
printf("输入错误");
break;
}
system("pause>nul");
goto menu;
}
还是要注意scanf_s的使用环境