資料結構 c++ 廣義表

來源:互聯網
上載者:User

標籤:

// 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++ 廣義表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.