簡體   English   中英

Python 在 class 中實現鏈表

[英]Python Implement linked list in a class

我正在嘗試在 python 中實現一個 class,每個 object 將是一個鏈表。 不使用類我可以像這樣反轉一個鏈表

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 的副本傳遞給反向 function。 我想在 class 中實現這個。 我嘗試過的東西。

class linked:
    def __init__(self):
        self.head = Node()
    
    def reverse(self):
        while head:
           print(head.data)
           head = head.next

如何在不丟失頭指針的情況下將 self.head 傳遞給 function 反向? 謝謝

由於您已經在使用獨立功能,因此一種方法是在 class 中使用它們。 當然,你也可以將它們重寫為 class 體。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM