UVa 11988 Broken Keyboard (a.k.a. Beiju Text) 数组模拟单向链表


UVa 11988 Broken Keyboard (a.k.a. Beiju Text) 数组模拟单向链表_第1张图片


#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int maxn = 100000 + 5;
//last表示最后一个字符是s[last],cur表示光标位于s[cur]后面
//Next[i]表示s[i]右面的字符编号(即在s中的下标)
//last其实相当于指针链表中的指向尾节点的指针,而Next[i]相当于
/*
指针链表节点
 struct node {
	char x;
	struct node* next;
 };
 中的next指针
 cur则类似于指向插入位置之前的一个节点的指针
*/
int last, cur, Next[maxn];
char s[maxn];

int main()
{
	while (~scanf("%s", s + 1)) {
		last = cur = 0; //0相当于空头节点
		Next[0] = 0; //类似于空头结点head->next = NULL;
		int len = strlen(s + 1);
		for (int i = 1; i <= len; i++) {
			if (s[i] == '[') cur = 0;
			else if (s[i] == ']') cur = last;
			else {
				//设this指向要插入的节点
				//类似this->next = cur->next;
				Next[i] = Next[cur];
				//类似cur->next = this;
				Next[cur] = i;
				if (cur == last) last = i; //类似尾指针偏移rear = rear->next;
				cur = i; //更新光标位置
			}
		}
		//这里head为空头节点
		//类似于for (node *i = head->next; i != NULL; i = i->next)
		for (int i = Next[0]; i != 0; i = Next[i]) {
			printf("%c", s[i]);
		}
		puts("");
	}
	return 0;
}



你可能感兴趣的:(链表,uva)