c++ 之广义表
2016-04-15 11:03
459 查看
广义表(Lists,又称列表)是一种非线性的数据结构,是线性表的一种推广。即广义表中放松对表元素的原子限制,容许它们具有其自身结构。它被广泛的应用于人工智能等领域的表处理语言LISP语言中。在LISP语言中,广义表是一种最基本的数据结构,就连LISP 语言的程序也表示为一系列的广义表。 代码实现如下 #pragma once #include<assert.h> #include<iostream> using namespace std; enum Type { HEAD, VALUE, SUB }; struct GeneralizedNode//节点包含 类型 值域 以及next指针 字表指针 { Type _type; GeneralizedNode *next;//指向同级的next union { int _value; GeneralizedNode *_Sublink; }; GeneralizedNode() :next(NULL), _value(0) {} }; class Generalize { public: Generalize(const char *str) { char *str1 = (char *)str; _head = CreatGeneralize(str1); } void print() { _print(_head); cout << endl; } size_t size() { return _size(_head); } size_t depth(); private: size_t _depth(GeneralizedNode *tmp)//最大嵌套层数 { int count = 0; } size_t _size(GeneralizedNode *tmp) { GeneralizedNode *cur = tmp; int count = 0; while (cur) { if (cur->_type == VALUE) { ++count; } else if (cur->_type == SUB) { count += _size(cur->_Sublink); } cur = cur->next; } return count; } void _print(GeneralizedNode *tmp) { GeneralizedNode *cur = tmp; while (cur) { if (cur->_type == HEAD) cout << '('; else if (cur->_type==VALUE) { cout << cur->_value; if (cur->next == NULL) cout << ')'; else { cout << ','; } } else { _print(cur->_Sublink); cout << ','; } cur = cur->next; } } GeneralizedNode* CreatGeneralize(char *&str) { while (*str) { if (*str == '(')//开始构成表。 { GeneralizedNode *_head = new GeneralizedNode; _head->_type = HEAD; GeneralizedNode *cur = _head; _head->_type = HEAD; ++str; while (*str) { if (IsValue(*str))//是一个数字 { GeneralizedNode *tmp = new GeneralizedNode; tmp->_type = VALUE; tmp->_value = *str; //++str; cur->next = tmp; cur = cur->next; ++str; } else if (*str == '(') { GeneralizedNode* sub = new GeneralizedNode; sub->_type = SUB; sub->_Sublink = CreatGeneralize(str); cur->next = sub; cur = cur->next; } else if (*str == ')') { ++str; return _head; } else { ++str; } } return _head; } return _head; } } bool IsValue(char p) { if (p >= 'a'&&p <= 'z' || p >= 'A'&&p <= 'Z' || p >= '0'&&p <= '9') return true; return false; } private: GeneralizedNode *_head; };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#数据结构之顺序表(SeqList)实例详解
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(七):数据结构详解
- Lua教程(二):C++和Lua相互传递数据示例
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题