/**************************************************************************
* 有n个元素存储在数组A[n]中,设计一个算法,实现将这n个元素循环向左移动k(0<k<n)位。
**************************************************************************/
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
//节点结构
typedef struct node{
ElementType data;
struct node *next;
}Qnode,*PQnode;
//链栈结构
typedef struct {
PQnode front, rear;
}LinkQueue,*PLinkqueue;
//链队初始化
PLinkqueue init_linkqueue(){
PLinkqueue queue = (PLinkqueue)malloc(sizeof(LinkQueue));
if(queue)
{
queue->front = NULL;
queue->rear = NULL;
}
return queue;
}
//判断链队为空;1空队列,0非空
int empty_linkqueue(PLinkqueue queue){
if(queue && (queue->front==NULL) && (queue->rear==NULL))
{
return 1;
}
else
{
return 0;
}
}
//入队列
int in_linkqueue(PLinkqueue queue, ElementType x){
PQnode p = (PQnode)malloc(sizeof(Qnode));
if(!p)
{
printf("内存溢出,不能申请新的节点空间\n");
return 0;
}
p->data = x;
p->next = NULL;
//要先判断队列中是否有元素,两者的的入队是有一些差别的
if(empty_linkqueue(queue))
{
queue->rear = p;
queue->front = p;
}
else
{
//入队的时候,在队尾插入元素
queue->rear->next = p;
queue->rear = p;
}
return 1;
}
//出队
int out_linkqueue(PLinkqueue queue, ElementType *x){
if(empty_linkqueue(queue))
{
printf("队空,无法出队\n");
return 0;
}
//出队首元素节点
*x = queue->front->data;
PQnode temp_front= queue->front;
//队首的下一个元素作为队首
queue->front = temp_front->next;
//释放出队节点
free(temp_front);
//如果队首为空,说明此时队列中没有元素节点了,则设置队尾也为空。
if(!queue->front)
{
queue->rear = NULL;
}
return 1;
}
//读取队首元素
int getFront_linkqueue(PLinkqueue queue, ElementType *x){
if(empty_linkqueue(queue))
{
printf("队空,无法获取队首 元素\n");
return 0;
}
*x = queue->front->data;
return 1;
}
//销毁队列。由于使用的是链表,因此,要释放每一个链表节点的空间
void destory_linkqueue(PLinkqueue *queue){
PQnode p;
if(*queue)
{
while((*queue)->front)
{
p = (*queue)->front;
(*queue)->front = (*queue)->front->next;
free(p);
}
free(*queue);
}
*queue = NULL;
}
void array_leftcircle_move(int a[], int n, int k){
int i;
PLinkqueue queue = init_linkqueue();
for(i=0;i<k;i++)
{
in_linkqueue(queue,a[i]);
}
//k=5,n=10
for(i=k;i<n;i++)
{
// printf("%d ",i);//0-9
a[i-k] = a[i];//05 16 27 38 49
}
// printf("\n");
for(i=0;i<10;i++)
{
printf("%d ",a[i]);//6 7 8 9 10 6 7 8 9 10
}
printf("\n");
i = n-k;//5
while(!empty_linkqueue(queue))
{
out_linkqueue(queue,&a[i]);//先进先出 把队列里的 第一位 第二位 第三位 第四位 第五位 依次出队赋值给a[5] a[6] a[7] a[8] a[9]
printf("%d ",a[i]);//1 2 3 4 5
i++;
}
printf("\n");
}
int main(){
int a[10], i, k = 5;
for(i=0;i<10;i++)
{
a[i] = i+1;
printf("%d ",a[i]);//1 2 3 4 5 6 7 8 9 10
}
printf("\n");
array_leftcircle_move(a,10,k);
for(i=0;i<10;i++)
{
printf("%d ",a[i]);//6 7 8 9 10 1 2 3 4 5
}
printf("\n");
return 0;
}
【入队&出队】一个例子让你看懂队列
于 2023-06-12 16:48:05 首次发布