Given a list,rotate the list to right by k places, where k is nonegative.

本文介绍了一种将链表向右旋转K个位置的算法实现。通过双指针技巧,该算法能在O(n)的时间复杂度内完成操作。文章详细解释了如何确定旋转步数并调整链表结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a list,rotate the list to right by k places, where k is nonegative.

给定一个列表,将列表向右旋转K个位置,其中K是非分隔的。

ListNode *rotateRight(ListNode *head, int k) {
	if (head == NULL || k < 0)
		return NULL;

	ListNode* cur = head;
	int count = 0;
	while (cur)
	{
		cur = cur->next;
		count++;
	}

	k = k % count;
	if (k == 0)
		return head;

	ListNode* fast = head;
	ListNode* slow = head;
	while (k--)
	{
		fast = fast->next;
	}

	while (fast->next)
	{

		fast = fast->next;
		slow = slow->next;
	}

	ListNode* newhead = new ListNode(0);
	cur = newhead;
	ListNode* p = slow;
	while (slow->next)
	{
		cur->next = slow->next;
		slow = slow->next;
		cur = cur->next;
	}
	while (head)
	{
		cur->next = head;
		head = head->next;
		cur = cur->next;
		if (head == p)
		{
			head->next = NULL;
		}
	}
	return newhead->next;

}

 

if args.flag_test == 'test': model.eval() model.load_state_dict(torch.load('./results/model.pkl')) pre_u = test_epoch(model, label_true_loader) prediction_matrix = np.zeros((height, width), dtype=float) for i in range(total_pos_true.shape[0]): prediction_matrix[total_pos_true[i,0], total_pos_true[i,1]] = pre_u[i] + 1 savemat('matrix.mat',{'P':prediction_matrix, 'label':label}) else: print("start training") tic = time.time() min_val_obj, best_OA = 0.5, 0 for epoch in range(args.epoches): scheduler.step() # train model model.train() train_acc, train_obj, tar_t, pre_t = train_epoch(model, label_train_loader, criterion, optimizer) OA1, AA_mean1, Kappa1, AA1 = output_metric(tar_t, pre_t) print("Epoch: {:03d} train_loss: {:.4f} train_acc: {:.4f}" .format(epoch+1, train_obj, train_acc)) if 'unmix' in args.model_name: # regularize unmix decoder model.unmix_decoder.apply(apply_nonegative) if (epoch % args.test_freq == 0) | (epoch == args.epoches - 1): model.eval() tar_v, pre_v = valid_epoch(model, label_test_loader, criterion, optimizer) OA2, AA_mean2, Kappa2, AA2 = output_metric(tar_v, pre_v) print("OA: {:.4f} AA: {:.4f} Kappa: {:.4f}" .format(OA2, AA_mean2, Kappa2)) print("*************************") if OA2 > min_val_obj and epoch > 10: model_save_path = os.path.join('./results/', args.dataset+'_'+args.model_name+'_p'+str(args.patches)+ '_'+str(round(OA2*100, 2))+'_epoch'+str(epoch)+'.pkl') torch.save(model.state_dict(), model_save_path) min_val_obj = OA2 best_epoch = epoch best_OA = OA2 best_AA = AA_mean2 best_Kappa = Kappa2 best_each_AA = AA2 toc = time.time() 这是后续的训练测试
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值