一、引子
Python的变量存储机制和c语言的大不相同。 C语言是一种静态类型语言,即变量的类型在编译时,并且在整个程序中保持不变;在c语言中,当执行
int a = 1000;
操作时,会在内存中开辟一个名字为a的空间,其中存储整型的1000
但python则不同,Python是一种动态类型语言,变量的类型是在运行时决定的。
a = 1000
执行上述语句时,python会在存储空间中开辟一个存储整型1000(对象)的空间,并让变量a去指向它。Python变量在定义时不需要指定类型,类型信息存储在变量引用的对象中。Python中一切皆对象,变量实际上是对对象的引用。
Python中的变量存储在名称空间中,名称空间是从名称到对象的映射。
这就决定了,你再python中,可以把一个整型、浮点型甚至是函数赋值给某一个变量,之后该变量会指向这些对象的存储空间,基于这一原理,我们便可以快乐地实现python链表操作
二、节点和链表的代码实现
一个链表是由若干个节点组成,对链表进行增删查改操作时,实质上是对节点操作,故我们需要先用python创造一个节点
class Node: # 创建一个节点类
def __init__(self, data):
self.data = data # 数据域
self.next = None # 指针域
这样我们就创建了一个节点类有点类似于c语言的结构体,之后创建一个新的节点时,只需把Node类实例化成对象即可
现在我们再来创建链表类,具体的我已经写在注释中
# 创建链表类
class Link:
def __init__(self):
headNode = Node(data=None)
self._head = headNode # 定义链表的头节点,初始值为空
def is_empty(self): # 判断链表是否为空
return self._head == None
def travel(self): # 遍历整个链表
cur = self._head
count = 0
while cur.next != None:
cur = cur.next
count = count + 1
print(f"第{count}个节点的内容为: ", cur.data)
def add_last(self, data): # 尾插法插入节点
newNode = Node(data=data)
cur = self._head
while cur.next != None:
cur = cur.next
cur.next = newNode
def add_head(self, data): # 头插法插入节点
newNode = Node(data=data)
newNode.next = self._head.next
self._head.next = newNode
def deleteId(self, id): # 根据下标号寻找节点并删除
count = 0
cur = self._head
while cur.next != None:
if count == id - 1:
cur.next = cur.next.next
print("删除成功")
break
count += 1
cur = cur.next
def deleteData(self, data): # 删除链表中的数据域为data的节点
cur = self._head
while cur.next != None:
if cur.next.data == data:
cur.next = cur.next.next
else:
cur = cur.next
def insertById(self, id, data): # 在指定索引处插入节点
cur = self._head
count = 0
newNode = Node(data=data)
while cur.next != None:
if count == id - 1:
newNode.next = cur.next
cur.next = newNode
break
count = count + 1
cur = cur.next
def updateById(self, id, data): # 修改下表为id的节点信息
count = 0
cur = self._head
while cur.next != None:
if count == id:
cur.data = data
break
count = count + 1
cur = cur.next
def searchById(self, id): # 查询下表为id的节点
count = 0
cur = self._head
while cur.next != None:
if count == id:
return cur.data
count = count + 1
cur = cur.next