1. 程式人生 > 其它 >陣列模擬連結串列

陣列模擬連結串列

題目:

分析:

由於字串長度達到10的5次方,操作設計頻繁插入,所以用普通的陣列遍歷肯定會超時。

解決方法是用連結串列,這裡用陣列模擬連結串列。注意模擬兩個字,這就要聯想到指標連結串列是怎麼實現的了,清楚原理後,用陣列模擬就不難了。

我們用next陣列來模擬連結串列,next[i]代表字串陣列第i元素的下一個元素的座標。這裡的關鍵是找到當前元素要插入的位置,我們用t變數來維護。為了方便我們輸入字串從第一個位置開始輸入,next[0]作為頭節點,當出現字元‘[’時t=0;當出現字元‘]’時,t=tail,tail為當前字串的尾部。

程式碼

#include<iostream>
#include
<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<set> #include<map> #include<vector> #include<queue> #include<stack> #include<utility> #include<unordered_map> using namespace std; typedef long long ll; typedef unsigned
long long ull; const int maxn=100000+5; const int inf=0x3f3f3f3f; const int mod = 1e9+7; char s[maxn]; int nxt[maxn]; int main() { while(scanf("%s",s+1)!=EOF){ nxt[0]=-1; int n=strlen(s+1); int t=0,tail=0;//printf("%d\n",strlen) for(int i=1;i<=n;i++){ if(s[i]=='
[')t=0; else if(s[i]==']')t=tail; else{ int p=nxt[t]; nxt[t]=i; nxt[i]=p; if(t==tail)tail=i; t=i; } } t=0; while(nxt[t]!=-1){ printf("%c",s[nxt[t]]); t=nxt[t]; } printf("\n"); } return 0; }