[C++] 广义表操作算法(广义表初始化、长度、深度、建立、输出) →→→→→进入此内容的聊天室

来自 , 2020-03-25, 写在 C++, 查看 123 次.
URL http://www.code666.cn/view/ed519dac
  1. #include<iostream.h>
  2. #include<stdlib.h>
  3. typedef char elemtype;
  4. struct glnode
  5. {
  6.         int tag;
  7.         union
  8.         {
  9.                 elemtype data;
  10.                 glnode *sublist;
  11.         };
  12.         glnode *next;
  13. };
  14.  
  15. int lenth ( glnode *gl )
  16. {
  17.         if ( gl!=NULL )
  18.                 return 1+lenth ( gl->next );
  19.         else
  20.                 return 0;
  21. }
  22.  
  23. int depth ( glnode *gl )
  24. {
  25.         int max=0;
  26.         while ( gl!=NULL )
  27.         {
  28.                 if ( gl->tag==1 )
  29.                 {
  30.                         int dep=depth ( gl->sublist );
  31.                         if ( dep>max )
  32.                                 max=dep;
  33.                 }
  34.                 gl=gl->next;
  35.         }
  36.         return max+1;
  37. }
  38.  
  39. void create ( glnode *&gl )
  40. {
  41.         char ch;
  42.         cin>>ch;
  43.         if ( ch=='#' )
  44.                 gl=NULL;
  45.         else if ( ch=='(' )
  46.         {
  47.                 gl=new glnode;
  48.                 gl->tag=1;
  49.                 create ( gl->sublist );
  50.         }
  51.         else
  52.         {
  53.                 gl=new glnode;
  54.                 gl->tag=0;
  55.                 gl->data=ch;
  56.         }
  57.         cin>>ch;
  58.         if ( gl==NULL )
  59.                 ;
  60.         else if ( ch==',' )
  61.                 create ( gl->next );
  62.         else if ( ( ch==')' ) || ( ch==';' ) )
  63.                 gl->next=NULL;
  64. }
  65.  
  66. void print ( glnode *&gl )
  67. {
  68.         if ( gl->tag==1 )
  69.         {
  70.                 cout<<'(';
  71.                 if ( gl->sublist==NULL )
  72.                         cout<<'#';
  73.                 else
  74.                         print ( gl->sublist );
  75.                 cout<<')';
  76.         }
  77.         else
  78.                 cout<<gl->data;
  79.         if ( gl->next!=NULL )
  80.         {
  81.                 cout<<',';
  82.                 print ( gl->next );
  83.         }
  84. }
  85.  
  86. void main( )
  87. {
  88.         glnode *g;
  89.         create ( g );
  90.         print ( g );
  91.         cout<<endl;
  92.         cout<<"gyb length:  "
  93.             <<lenth ( g->sublist ) <<endl;
  94.         cout<<"gyb depth:  "
  95.             <<depth ( g->sublist ) <<endl;
  96. }
  97.  

回复 "广义表操作算法(广义表初始化、长度、深度、建立、输出)"

这儿你可以回复上面这条便签

captcha