UVA11988 Broken Keyboard 破损的键盘

本文介绍了解决 UVA-11988 问题的方法,通过使用链表而非数组来提高插入操作的效率,避免了在数组头部插入导致的时间复杂度过高的问题。文中提供了一个具体的 C++ 实现示例。

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

题目链接:https://vjudge.net/problem/UVA-11988

题解:很明显,不能直接使用数组进行插入,因为普通的数组在头插入时效率非常低。所以本题实现的存储模型应选择链表。书中提供的是使用数据模拟链表的一种方法,我还没有掌握,就直接写了一个链表。特别注意,end指针必须要在插入时进行记录,如果在‘]’的时候再遍历到最后一个,仍然会超时。

代码:

#include<iostream>
#include<string>

using namespace std;

const int maxn = 1e5 + 10;

struct letter {
	char l;
	letter *next;
};


int main() {

	//freopen("input.txt","r",stdin);
	//freopen("output.txt", "w", stdout);

	string s;
	while (cin >> s)
	{

		letter *home = new letter(), *cursor = home, *end = home;

		for (int i = 0; i < s.size(); i++)
		{
			if (s[i] == '[') {
				cursor = home;

			}else if (s[i] == ']') {
				cursor = end;
			}
			else {
				letter *l = new letter();
				l->l = s[i];

				letter *p = cursor->next;
				cursor->next = l;

				l->next = p;
				cursor = l;
				if (cursor->next == NULL) {
					end = cursor;
				}
			}
		}

		for (letter *it = home->next; it != NULL; it = it->next)
		{
			cout << it->l;
		}
		cout << endl;
	}

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值