標籤:
// CTest.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <iostream>#include <string.h>#include <stdio.h>using namespace std;typedef char ElemType;struct GLNode{ bool tag; //標誌位 union{ //範圍或子表的表頭指標域 ElemType data; GLNode *sublist; }; GLNode *next;};//用來測試 (a,(b,(c)),(#),((d,e))),f,(g));//求廣義表的長度 廣義表的長度就是求單鏈表的長度int Lenth(GLNode *GL){ if(GL!=NULL){ return 1+Lenth(GL->next); }else{ return 0; }}//求廣義表的長度 廣義表的長度就是求單鏈表的長度int Depth(GLNode *GL){ int max=0; while(GL!=NULL){ if(GL->tag==true){ int dep = Depth(GL->sublist); if(dep>max) max=dep; } GL=GL->next; } return max+1;}//建立廣義表void Create(GLNode* &GL){ char ch;//讀一個字元 cin>>ch; //若輸入#,則置GL為空白 if(ch==‘#‘) GL=NULL; //若輸入為左括弧則建立由GL所指向的子表結點並遞迴構造字表 else if(ch=‘(‘){ GL = new GLNode; GL->tag=true; Create(GL->sublist); } else{ GL=new GLNode; GL->tag=false; GL->data=ch; } //此處讀入的字元必為逗號,右括弧或分號 cin>>ch; //若GL為空白,此時輸入的字元必然為‘)‘,則什麼都不用做 if(GL==NULL); //若輸入為逗號則遞迴構造後繼表 else if(ch==‘,‘) Create(GL->next); //若輸入為右括弧或分號則置GL的後繼指標域為空白 else if((ch==‘)‘)||(ch==‘;‘)) GL->next=NULL;}//列印輸出廣義表void Print(GLNode *GL){ if(GL->tag==true){ cout<<‘(‘; //對於表結點,則先輸出左括弧,作為開始符號 if(GL->sublist==NULL) cout<<‘#‘; //若字表指標為空白,則輸出‘#’字元 else Print(GL->sublist);//若為非空字表,則遞迴輸出此表 cout<<‘)‘; //當一個字表輸出結束後,應輸出右括弧作為終止符 } else cout<<GL->data; //對於單元素結點,輸出該結點的值 if(GL->next!=NULL){ //輸出GL結點的後繼表 cout<<‘,‘; //先輸出括弧及分割符後 Print(GL->next); //再遞迴輸出後繼表 }}int _tmain(int argc, _TCHAR* argv[]){ GLNode *g=NULL; Create(g); Print(g); cout<<endl; cout<<"廣義表的長度:"<<Lenth(g->sublist)<<endl; cout<<"廣義表的深度:"<<Depth(g->sublist)<<endl; system("pause"); return 0;}
資料結構 c++ 廣義表