首页 > 解决方案 > 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?谢谢

标签: 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

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)

推荐阅读