采用"头尾法存储广义表,实现以下广义表的操作: 1.Status CreateGList( GList &L, char *S ) // 根据字符串 S 表示的广义表内容建立广义表数据结构; 2.GList GetHead( GList L) // 取表头运算 3.GList GetTail( GList L) // 取表尾运算 4.void DestroyGList( GList &L) // 销毁广义表 L 5.void PrintGList( GList L) // 显示广义表 L 内容
程序运行时,首先输入一个广义表,表中的原子是小写字母。随后可以交替输入取表头或取表尾指令(分别用 1 和 2 表示),取的结果替代当前广义表,并释放相应的资源(需将释放资源信息输出)。当广义表是空或是原子时,程序停止运行。
例:(下面的黑体为输入)
((a,()),c,d)
generic list: ((a,()),c,d)
1 destroy tail free list node generic list: (a,())
2 free head node free list node generic list: (())
1 destroy tail free list node
generic list: ()
测试输入
(a,(b,(c,d)),e,f) 2 1 2 1 1 测试输出 generic list: (a,(b,(c,d)),e,f) free head node free list node generic list: ((b,(c,d)),e,f) destroy tail free list node generic list: (b,(c,d)) free head node free list node generic list: ((c,d)) destroy tail free list node generic list: (c,d) destroy tail free list node generic list: c 源代码 #include <iostream> #include <cstring> #include <cstdio> #define length 100 using namespace std; int main() { char M[length] = {0}; char N[length] = {0}; cin >> M; cout<<"generic list: "<<M<<endl ; while(1){ int len = strlen(M); memset(N , 0 , sizeof(N)); if(len==1){ if('a'<=M[0] && M[0]<='z') break; } else if(len == 2){ if(M[0]=='(' && M[1]==')') break; } int T=0 , R1 = 0 , i , j ; int L2 = 0 , R2 = 0; cin>>T; int W = 0; if(M[0]=='(' && M[1]=='('){ W = 1; for(int i = 2 ; i < len ;i++){ if(M[i] == '(') L2++; if(M[i] == ')') R2++; if(R2 == L2 + 1){ R1 = i; break; } } } if(T == 1) { if(W){ for( i = 1 , j = 0 ; i <= R1 ; i++ , j ++){ N[j] = M[i]; } N[j+1] = '\0'; strcpy(M , N); } else { M[0] = M[1]; M[1] = '\0'; } cout <<"destroy tail\nfree list node\ngeneric list: "; cout<<M<<endl; } else if(T == 2){ if(W){ N[0] = '('; int Empty = 1; for(int i = R1 +2 , j = 1 ;i < len ;i++ , j++){ N[j] = M[i]; Empty = 0; } if(Empty){ N[1] = ')'; N[2]='\0'; } else N[j+1] = '\0'; strcpy(M , N); } else{ N[0] = '('; for(i = 3 , j = 1 ; i < len ;i++, j++) N[j] = M[i]; N[j+1] = '\0'; strcpy(M , N); } cout<<"free head node\nfree list node\ngeneric list: "; cout<<M<<endl; } } return 0; }