这题尝试了两种方法,一是书上说的用数组来实现链表相关操作,一种是利用指针形式的链表实现
使用数组模拟链表
1.使用字符数组c储存一行中每个字符的值
2.使用数组next储存下一个字符的位置,可以看成c[i]和next[i]共同构成链表中的一个结点(所以next[0],c[0]对应的是头节点)
3.设当前字符的上个字符所在位置为cur初始值为0,当字符不是‘[‘和’]’时利用cur做普通的插入操作。当字符是‘[‘时,cur=0.当字符是‘]’时,cur等于最后一个字符编号last
4.最后输出
代码实现
#include<iostream>
#include<string>
using namespace std;
int main()
{
string input;
while (cin >> input)
{
char c[100001]; //存储节点数据
int next[100001];//存储节点后继信息
next[0] = 0;//初始头指针指向自身,0也为结尾标志
int len = input.size();
int cur=0;//光标前一个位置
int last=0;// 最后位置
for (int i = 1; i <= len; i++)
{
c[i] = input[i - 1];
}
for (int i = 1; i <= len; i++)
{
if (c[i] == '[')
{
cur = 0;
}
else if (c[i] == ']')
{
cur=last;
}
else
{
//模拟链表插入操作
next[i] = next[cur];
next[cur] = i;
if (cur == last) //更新最后一个字符的编号
last = i;
cur = i;
}
}
for (int i = next[0]; i!=0; i=next[i])
{
cout << c[i];
}
cout << endl;
}
system("pause");
return 0;
}
使用基于指针的链表方式解决
要注意的是,当碰到‘]’需要移动到文本结尾的时候,本来我是想通过遍历当前链表,找到最后一个节点,并返回指针来实现的,不过发现似乎会超时。所以还是定义了一个last节点,专门保存最后一个节点的值
代码实现
#include<iostream>
#include<string>
using namespace std;
typedef struct linknode { //节点
char c;
linknode *next;
linknode() { c = '0';
next = NULL;
}
}node;
class list
{
private:
node *head;//头指针
public:
list() {
head = new node;
}
~list() {
node *p = head;
while (p!= NULL)
{
node *temp = p;
p = p->next;
delete []temp;
}
}
node* returnHead()
{
return head;
}
node* returntail()
{
node *p = head;
while (p->next != NULL)
{
p = p->next;
}
return p;
}
node* insert(node *cur,node *needin)
{
needin->next = cur->next;
cur->next = needin;
return needin;
}
void printList()
{
node *p = head->next;
while (p!= NULL)
{
cout << p->c;
p = p->next;
}
}
};
int main()
{
string input;
while (cin >> input)
{
list listA;
int len = input.size();
node *cur = listA.returnHead();
node *last = listA.returnHead();
for (int i = 0; i < len; i++)
{
if (input[i] == '[')
{
cur = listA.returnHead();
}
else if (input[i] == ']')
{
cur = last; //不能通过returntail实现,因为会超时
}
else
{
node *temp=new node;
temp->c = input[i];
temp->next = NULL;
if (cur == last)
{
cur = listA.insert(cur, temp);
last = cur;
}
else
{
cur = listA.insert(cur, temp);
}
}
}
listA.printList();
cout << endl;
}
system("pause");
return 0;
}