1. 程式人生 > >實現廣義表的各種基本運算演算法

實現廣義表的各種基本運算演算法

/*algo8-1.cpp*/
#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct lnode
{
 int tag;/*結點型別標識*/
 union
 {
  ElemType data;
  struct lnode *sublist;
 }val;
    struct lnode *link;/*指向下一個元素*/
}GLNode;

GLNode *CreatGL(char * &s)/*由串s建立一個廣義表*/
{
 GLNode *h;
 char ch;
 ch=*s;/*取一個掃描字元*/
 s++;/*串指標後移一位*/
 if(ch!='\0')/*串未結束判斷*/
 {
  h=(GLNode *)malloc(sizeof(GLNode));/*建立一個新結點*/
  if(ch=='(')/*當前字元為左括號時*/
  {
   h->tag=1;/*新結點作為表頭結點*/
   h->val.sublist=CreatGL(s);/*遞迴構造子錶鏈到表頭結點*/
  }
  else if(ch==')')/*遇到')'字元,子表為空*/
   h=NULL;
  else
  {
   h->tag=0;/*新結點作為原子結點*/
   h->val.data=ch;
  }
 }
 else h=NULL;/*串結束,子表為空*/
 ch=*s;/*取下一個掃描字元*/
 s++;/*串指標後移一位*/
 if(h!=NULL)/*串未結束判斷*/
  if(ch==',')/*當前字元為','*/
   h->link=CreatGL(s);/*遞迴構造後續子表*/
  else /*串結束*/
   h->link=NULL;/*處理表的最後一個元素*/
  return h;/*返回廣義表指標*/
}

int GLLength(GLNode *g)/*求廣義表q的長度*/
{
 int n=0;
 g=g->val.sublist;/*g指向廣義表的第一個元素*/
 while(g!=NULL)
 {
  n++;
  g=g->link;
 }
 return n;
}

int GLDepth(GLNode *g)/*求帶頭結點的廣義表g的深度*/
{
 int max=0,dep;
 if(g->tag==0)
  return 0;
 g=g->val.sublist;/*g指向第一個元素*/
 if(g==NULL)/*為空表時返回1*/
  return 1;
 while(g!=NULL)/*遍歷表中的每一個元素*/
 {
  if(g->tag==1)/*元素為子表的情況*/
  {
   dep=GLDepth(g);/*遞迴呼叫求出子表的深度*/
   if(dep>max)
    max=dep;/* max為同一層所求過的子表中深度的最大值*/
  }
  g=g->link;/*使g指向下一個元素*/
 }
 return (max+1);/*返回表的深度*/
}

void DispGL(GLNode *g)/*輸出廣義表g*/
{
 if(g!=NULL)/*表不為空判斷*/
 {
  if(g->tag==1)/*為表結點時*/
  {
   printf("(");/*輸出'('*/
   if(g->val.sublist==NULL)
    printf(" ");/*輸出空子表*/
   else
    DispGL(g->val.sublist);/*遞迴輸出子表*/
  }
  else
   printf("%c",g->val.data);/*為原子時輸出元素值*/
  if(g->tag==1)
   printf(")");/*為表結點時輸出")"*/
  if(g->link!=NULL)
  {
   printf(",");
   DispGL(g->link);/*遞迴輸出後續表的內容*/
  }
 }
}

/*exp8-1.cpp*/
#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct lnode
{
 int tag;/*結點型別標識*/
 union
 {
  ElemType data;
  struct lnode *sublist;
 }val;
    struct lnode *link;/*指向下一個元素*/
}GLNode;

extern GLNode *CreatGL(char * &s);
extern int GLLength(GLNode *g);
extern int GLDepth(GLNode *g);
extern void DispGL(GLNode *g);
void main()
{
 GLNode *g;
 char *str="(b,(b,a,a),((a,b),c))";
 g=CreatGL(str);
 printf("廣義表g:");DispGL(g);printf("\n");
 printf("廣義表g的長度:%d\n",GLLength(g));
 printf("廣義表g的深度:%d\n",GLDepth(g));
 printf("\n");
}