链表,C语言程序
我写了一个用pascal分析代码的程序。我已经完成了文本的工作,现在我必须将结果保存在链表中,我知道如何做。在我的计划中,我有以下要素:链表,C语言程序,c,linked-list,analysis,lexical-analysis,C,Linked List,Analysis,Lexical Analysis,我写了一个用pascal分析代码的程序。我已经完成了文本的工作,现在我必须将结果保存在链表中,我知道如何做。在我的计划中,我有以下要素: variables(name, type) constants(name) typedef(name and components) procedures(local variables, constants and types) function (its var, const and types) 在我看来,创建5个列表并不是一个有效的解决方案。你能给我
variables(name, type)
constants(name)
typedef(name and components)
procedures(local variables, constants and types)
function (its var, const and types)
在我看来,创建5个列表并不是一个有效的解决方案。你能给我一个技巧,如何为这些元素创建一个包含不同数量组件的列表吗?
非常感谢5列表并不一定效率低下,除非您想在所有列表中搜索名称或其他内容
另一种方法是用一种通用的方式将所有信息存储在一个列表中。你可以列举你储存的东西 这取决于你所说的“高效”是什么意思 如果希望将所有不同的元素都包含在同一个列表中,则需要将类型信息添加到元素中,当然,在查找某些内容时,需要花时间过滤掉所有错误的元素 因此,拥有不同类型元素的单独集合似乎更有效 你应该这样做:
typedef struct Element Element;
struct Element {
Element *next;
};
typedef struct {
char *name;
VariableType type;
} ElementVariable;
/* ... and so on */
然后,您可以拥有各种链接列表标题:
ElementVariable *variables;
ElementConstant *constants;
由于每个
ElementXXX
类型都以元素开始,因此您可以编写相当通用的链表代码来处理所有不同的类型。我不知道您想对列表做什么,但这里有一个想法:创建一个树,其中兄弟节点的行为类似于喜欢列表中的常规next
项,并且子节点提供其他信息,如复合类型或函数参数的条目
所以结构看起来像这样:
struct Entity {
const char *id;
enum Type type;
char is_const;
char is_var;
/* ... whatever ... */
struct Entity *next;
struct Entity *child;
};
[var x: integer]
|
[proc: procedure] -> [var res: integer]
| |
| [x: integer]
| |
| [y: integer]
|
[type date: record] -> [dd: integer]
|
[mm: integer]
|
[yy: integer]
所以如果你有
var x: integer;
procedure proc(var res: integer, x, y: integer); forward;
type date = record
dd, mm, yy: integer;;
end;
您的树将如下所示:
struct Entity {
const char *id;
enum Type type;
char is_const;
char is_var;
/* ... whatever ... */
struct Entity *next;
struct Entity *child;
};
[var x: integer]
|
[proc: procedure] -> [var res: integer]
| |
| [x: integer]
| |
| [y: integer]
|
[type date: record] -> [dd: integer]
|
[mm: integer]
|
[yy: integer]
在这里,箭头->
表示子项,竖条|
表示同级项或列表中的下一项
左侧的元素构成主要列表,其中包括第一级(全局范围)符号。下一级表示父元素的范围。例如,dd
仅在记录date
中已知。这本质上是一个多级链表,很容易为任意数量的函数参数或记录项展开