单向队列代码

单向队列代码

#include<stdio.h>
#include<stdlib.h>


typedef struct Queue {
	int* queue;//队列数组
	int rear;//队尾指针
	int front;//队头指针
	int maxSize;//最大长度
}queue;

queue* initQueue()
{
	queue* list = (queue*)malloc(sizeof(queue));
	list->queue = (int*)malloc(sizeof(int) * 5);
	list->rear = list->front = 0;
	list->maxSize = 5;
	return list;
}

/*

插入队列
int key 待插入的元素

queue* list 需要插入哪个队列
*/
void insert_queue(int key,queue* list)
{
	if ((list->rear + 1 )%list->maxSize != list->front)
	{
		list->queue[list->rear] = key;
		list->rear = ((list->rear) + 1) % list->maxSize;
	}
	else
	{
		//满了
	}
}

void delete_queue(queue* list)
{
	if (list->front != list->rear)
	{
		list->front = ((list->front) + 1) % list->maxSize;
	}
	else {
		//队空 不能删
	}
}

//进行输出
void printf_queue(queue* list)
{
	//先拿到队头和队尾指针
	int temp_front = list->front;
	int temp_rear = list->rear;

	for (int i = temp_front; i != temp_rear ; i = (i + 1) % list->maxSize)
	{
		printf("%d ", list->queue[i]);
	}
	
}
以下是单向最短路径的Python代码,使用Dijkstra算法实现: ```python import heapq from collections import defaultdict def dijkstra(graph, start): distances = {node: float('inf') for node in graph} distances[start] = 0 queue = [(0, start)] while queue: current_distance, current_node = heapq.heappop(queue) if current_distance > distances[current_node]: continue for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(queue, (distance, neighbor)) return distances # 示例代码 graph = defaultdict(dict) graph['A']['B'] = 3 graph['A']['C'] = 2 graph['B']['C'] = 1 graph['B']['D'] = 5 graph['C']['D'] = 2 graph['D']['E'] = 4 distances = dijkstra(graph, 'A') print(distances) # 输出 {'A': 0, 'B': 3, 'C': 2, 'D': 4, 'E': 8} ``` 上述代码中,我们使用了优先队列(Python中的heapq模块)来实现Dijkstra算法。我们首先初始化一个distances字典来存储每个节点到起点的距离,初始值为无穷大。然后我们将起点的距离设置为0,并将其插入到优先队列中。在每次循环中,我们弹出距离起点最近的节点并更新其周围节点的距离。如果新的距离比原来的距离更短,则将其更新到distances字典中,并将其插入到优先队列中。最后,我们返回distances字典,其中每个节点的值为该节点到起点的最短距离。 在示例代码中,我们创建了一个简单的图,并使用起点'A'调用dijkstra函数。函数返回了一个distances字典,其中每个节点的最短距离已经计算出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tian Meng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值