我们现在计划构造一个四元式的存储链表,将语法分析器生成的四元式存储进来。

比如语法 x = 3 + 4,则有四元式

head -> [0,[+,3,4,T1]] - > [1,[=,T1,None,x]]

每一个链表默认自带一个不重名的标记,我们可以根据这个标记来寻找

 1 class Node:
 2     index = 0
 3
 4     def __init__(self, op=None, arg1=None, arg2=None, result=None):
 5         self.data = (int(Node.index), [op, arg1, arg2, result])
 6         Node.index += 1
 7         self.next = None
 8
 9
10 class LinkList:
11     tail = None
12     index = 0
13
14     def __init__(self, name):
15         self.head = Node()
16         self.name = name + str(LinkList.index)
17         LinkList.index += 1
18         LinkList.tail = self.head
19
20     def insert_node(self, node):
21         LinkList.tail.next = node
22         LinkList.tail = node
23
24     def traverse_list(self):
25         p = self.head.next
26         print("这个链表的序号为:", self.name)
27         while p is not None:
28             print("序号:", p.data[0],
29                   "[", p.data[1][0], ",",
30                   p.data[1][1], ",",
31                   p.data[1][2], ',',
32                   p.data[1][3], "]")
33             p = p.next
34
35
36 if __name__ == '__main__':
37     List = LinkList("name")
38     List.insert_node(Node(1, 2, 3, 4))
39     List.insert_node(Node(5, 6, 7, 8))
40     List.insert_node(Node(9, 10, 11, 12))
41     List.traverse_list()
42
43     List = LinkList("name")
44     List.insert_node(Node(1, 2, 3, 4))
45     List.insert_node(Node(5, 6, 7, 8))
46     List.insert_node(Node(9, 10, 11, 12))
47     List.traverse_list()
12-28 12:07