链表是一种由一系列节点组成的数据结构, 每个节点都有指向下个节点的指针。这种结构就不需要连续的内存去存储,但只要找到起始节点(头节点),整个链表的数据都可以被依次访问。
在python3中,创建链表的过程可以粗略分为定义单节点,定义空链表,向空链表填充数据几个步骤
(来自https://www.educative.io/edpresso/how-to-create-a-linked-list-in-python)
定义单节点:
class Node:
# constructor
def __init__(self, data, next=None):
self.data = data
self.next = next
这个节点Node类的构造函数_init_决定了Node可以接受外界输入的数据data,并存在自身的data变量中。next变量则去存储指向下一个Node的指针。
定义空链表:
class LinkedList:
def __init__(self):
self.head = None
# insertion method for the linked list
def insert(self, data):
newNode = Node(data)
if(self.head):
current = self.head
while(current.next):
current = current.next
current.next = ne