python - Python在一个类中实现链表
问题描述
我正在尝试在 python 中实现一个类,每个对象都是一个链表。不使用类我可以像这样反转一个链表
class Node:
def __init__(self):
self.data = 0
self.next = None
def reverse(cur):
if cur == None:
return
reverse(cur.next)
print(cur.data,end =" ")
def printt(head):
cur = head
while cur is not None:
print(cur.data, end =" ")
cur = cur.next
def insert(head, data):
cur = head
while cur.next!=None:
cur = cur.next
newnode = Node()
newnode.data = data
cur.next= newnode
head = Node()
for i in range(1,5):
insert(head,i)
print("Complete list")
printt(head)
print()
print("reverse list")
reverse(head)
print()
print("head is ",head.data)
head = Node()
reverse(head)
这里将 head 的副本传递给 reverse 函数。我想在一个类中实现它。我尝试过的东西。
class linked:
def __init__(self):
self.head = Node()
def reverse(self):
while head:
print(head.data)
head = head.next
如何在不丢失头指针的情况下将 self.head 传递给函数 reverse?谢谢
解决方案
由于您已经在使用独立功能,因此一种方法是在类中使用它们并使用它们。当然,你也可以将它们重写为类体。
class Node:
def __init__(self):
self.data = 0
self.next = None
def reverse(cur):
if cur == None:
return
reverse(cur.next)
print(cur.data,end =" ")
def printt(head):
cur = head
while cur is not None:
print(cur.data, end =" ")
cur = cur.next
def insert(head, data):
cur = head
while cur.next!=None:
cur = cur.next
newnode = Node()
newnode.data = data
cur.next= newnode
class Linked:
def __init__(self):
self.head = Node()
def insert(self,data):
insert(self.head,data)
def reverse(self):
reverse(self.head)
def printt(self):
printt(self.head)
linked = Linked()
for i in range(1,5):
linked.insert(i)
print("Complete list")
linked.printt()
print()
print("reverse list")
linked.reverse()
print()
print("head is ",linked.head.data)
推荐阅读
- node.js - 猫鼬更新很多不适用于 node.js 中的 $cond
- php - 很难从这个数组中取出元素
- javascript - 在 Rails 应用程序中重新加载页面之前,JS/Jquery 将无法工作
- mongodb - Mongodb组,然后是子组
- excel - 是否可以从 Excel 中的 TODAY() 函数中减去 2 小时?
- java - 如何在 Install4j 中实现安装功能选项屏幕?
- python - python re.findall 返回空列表
- python - 需要帮助转换这个数字系统
- coq - Coq 为单射函数定义类型构造函数
- java - 杰克逊根据通用类型设置元素名称