首先,这是从元素列表中创建双链表的函数。
假设我们有一个字符串元素列表:
testList =['A lot', 'Very ^much', 'Try it', 'Nop']
现在要从testList 中构建双向链表,我们这样做如下:
# Build node function
def getNode(data):
return [data, None, None]
# Build the doubly linked list
def construct_double_list(testList):
nxt, prvs = 1, 2
start, end = None, None
for line in testList:
next_node = getNode(line)
if start is not None:
end[nxt] = next_node
next_node[prvs] = end
end = next_node
else:
start = next_node
end = next_node
return start, end
如果你运行上面的函数构建器,双向链表(双向迭代)将是:
dll = dll = ['A lot', ['Very ^much', ['Try it', ['Nop', None, [...]], [...]], [...]], None]
我昨天已经这样做了,但是今天早上我在尝试解决光标问题时遇到了困难。一段时间后,我刚刚开始工作(终于!)。这是创建光标作为指向节点(包含当前行)的指针的函数以及该行中的位置,如下所示:
def cursor():
cursor = (None, None)
start, end = construct_double_list(testList)
node = start
while node is not None:
line = node[0]
if '^' in line:
pointer1 = node
pointer2 = line.index('^')
node = node[1]
cursor = (pointer1, pointer2)
return cursor
如果打印上面的cursor()函数:
print(cursor())
你得到:
(['Very ^much', ['Try it', ['Nop', None, [...]], [...]], ['A lot', [...], None]], 5)
# Node 1 and string index 5
现在我可以创建一些有用的函数来编辑数据、修改、添加、删除、交换元素、在双向链表的字符串元素中交换字符……等等。