在大学学习数据结构的时候,都是用c语言实现的,c语言对于指针的管理非常灵活,实现数据结构非常清晰直观,那么如何用Python实现那,一起来学习吧!
链表的结构这里就不介绍了,可以查看数据结构
首先编写一个链表类
#定义链表
class ListNode():
def __init__(self,data):
self.data = data
self.next = None
创建两个节点,并输出节点地址
node1 = ListNode(1)
node2 = ListNode(2)
node1.next = node2
print(id(node1.data))
print(id(node1.next.data))
print(id(node2.data))
结果
140710799142656
140710799142688
140710799142688
第一个地址是节点1的数据域,第二个地址是节点1的指针域,第三个地址是节点2的数据域
输出链表对象的内存地址
node1 = ListNode(1)
node2 = ListNode(2)
node1.next = node2
print(id(node1.data))
print(id(node1.next))
print(id(node2))
结果
140710799142656
2529486288544
2529486288544
结合上面连个实例,可以看到,在python中的“=”号,其实就是拷贝对象内存地址,所以我们就可以用“=”,实现c语言指针的作用
链表的使用
#定义链表
class ListNode():
def __init__(self,data):
#链表初始化为空
self.head = data
self.next = None
#判断链表是否为空
def isempty(self):
if self == None:
return True
elif self.head == None:
return True
#在链表尾添加元素
def List_add_tail(self,data):
if isempty(self):
self.head = data
else:
current = self
while current.next !=None:
current = current.next
current.next = ListNode(data)
#在链表头部添加元素
def List_add_head(self,data):
if isempty(self):
self.head = data
else:
head = ListNode(data)
head.next = self
return head
#遍历链表
def List_search(self,data):
if isempty(self):
return False
else:
p = self
while p != None:
if p.head == data:
return True
p = p.next
return False
#删除链表
def List_remove(self,data):
if isempty(self):
return False
elif self.next == None:
self = None
else:
p = self.next
phead = self
while p != None:
if p.head == data:
phead.next = p.next
p = p.next
phead = phead.next
#连接两个链表
def Link_nodes(list1,list2):
if list1 == None and list2 != None:
return list2
elif list2 == None and list1 != None:
return list1
else:
head = ListNode(None)
while list1 is not None or list2 is not None:
List_add_tail(head,list1.head)
List_add_tail(head, list2.head)
list1 = list1.next
list2 = list2.next
if list1 == None:
while list2 != None:
List_add_tail(head, list2.head)
elif list2 == None:
while list1 != None:
List_add_tail(head, list1.head)
return head
if __name__=='__main__':
#链表初始化为空
nodes = ListNode(None)
nodes1 = ListNode(None)
#添加三个节点
for i in range(3):
List_add_tail(nodes,i)
for i in range(3):
List_add_tail(nodes1,i)
#nodes=List_add_head(nodes,4)
#遍历的指针
#p = nodes
# while p != None:
# print(p.head)
# p = p.next
#搜索节点
#search = List_search(nodes,2)
#print(search)
#删除元素
#List_remove(nodes,1)
#p = nodes
#while p != None:
# print(p.head)
# p = p.next
a = Link_nodes(nodes,nodes1)
while a != None:
print(a.head)
a = a.next
由于Python中不能定义指针,所以两链表连接时,需要重新创建链表,与c语言的写法不一样