簡體   English   中英

Python - 將鏈表類模塊反轉為輸入

[英]Python - reversing a linked list class module as input

我正在研究一個接受鏈表作為輸入的問題,此時我甚至不知道如何設置示例鏈表。

我最初的問題是理解以下指令:

Write a function that accepts a linked list as input, then reverses that linked list.

這是否僅僅涉及定義“反向摘要”作為以下內容的一部分,或者是否有其他方法來匯總Python中的鏈接列表:

class Node(object):

    # Initialize with a single datum and pointer set to None

    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

    # Returns the stored data

    def get_data(self):
        return self.data

    # Returns the next node

    def get_next(self):
        return self.next_node

    # Reset the pointer to a new node

    def set_next(self, new_next):
        self.next_node = new_next

    def set_data(self, data):
        self.data = data

class LinkedList(object):

    # Top node in the list created on __init__

    def __init__(self, head=None):
        self.head = head

    # Take in the new node and point the new node to the prior head O(1)

    def insert(self, data):
        new_node = Node(data)
        new_node.set_next(self.head)
        self.head = new_node

    # Counts nodes O(n)

    def size(self):
        current = self.head
        count = 0
        while current:
            count += 1
            current = current.get_next()
        return count

    # Checks each node for requested data O(n)

    def search(self, data):
        current = self.head
        found = False
        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                current = current.get_next()
        if current is None:
            raise ValueError("Data not in list")
        return current

    # Similar to search, leapfrogs to delete, resetting previous node pointer to point to the next node in line O(n)

    def delete(self, data):
        current = self.head
        previous = None
        found = False
        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                previous = current
                current = current.get_next()
        if current is None:
            raise ValueError("Data not in list")
        if previous is None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

看來您的基本鏈接列表類的所有代碼都在那里。 您只需要反轉您的鏈接列表。 反轉鏈表如下。

[1] - > [2] - > [3] - > NULL

你可以知道1是Head,3是Tail(意思是它是鏈表中的最后一個節點,因為它在Python中指向NULL或None)。 你需要做的是找出一些算法,它將采用該鏈表並產生這個結果。

[3] - > [2] - > [1] - > NULL

現在3是頭,1是尾。

所以使用Psuedocode:

Initalize 3 Nodes: prev, next, and current
current = head
prev = None
next = None
While current != None
    next = current.next
    current.next = prev
    prev = current
    current = next
head = prev

暫無
暫無

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

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