簡體   English   中英

在 python 鏈表的頭部插入

[英]Insert at head in python linked list

我正在使用 Python 在鏈表的頭部實現插入。 我正在參考本指南 對於案例 2,我發現我必須添加return self.head以使驅動程序代碼正確插入頭部,否則它不會終止。 這是為什么? 我認為第一行就足夠了,因為我正在調用此方法來修改鏈表。 為什么我需要返回?

這是在節點之前插入的代碼:

class LinkedList:
    # note nodes = Node set the default (no argument) initialization
    def __init__(self, nodes = None):
        self.head = None
        if nodes is not None:
            # .pop(index) method remove the element from an array-like container and return it
            node = Node(nodes.pop(0))
            self.head = node
            # loop through the rest elements in nodes (2nd now became the 1st in nodes)
            for elem in nodes:
                node.next = Node(elem)
                node = node.next

    def insert_before(self, targetn_data, newn):
        # case1: empty list
        if self.head is None:
            raise Exception('empty llist')
            
        # case2: insert before head (newn becomes new head)
        if targetn_data == self.head.data:
            print(f'inserting {newn} at the head')
            newn.next = self.head
            self.head = newn
            ################# Why? ##################
            return self.head
            #########################################

        # case3: in between. use runner technique
        ...

驅動代碼:

def main():
    nodes = [1, 2, 3, 4, 5, 6]

    # instantiate a linked list using __init__ method we defined
    llist = LinkedList(nodes)

    # insert_before driver code
    llist.insert_before(1, Node(100))
    llist.insert_before(6, Node(90))
    print(f'prints out the llist after insert_before: \n {llist}\n')
  • function 的實現取決於您。 它可以改變。
  • 而關於他為什么使用回報是剛出來 function 或其他任何其他步驟#case3 他們將運行這是意料之外的。
  • 通常,當您編寫代碼比編寫 if-else 子句時,最好先使用 exit 或執行剩余的代碼。 (這里退出是返回語句)。
    • 這種編碼方式對於其他看到代碼的開發人員來說很容易理解,這樣他們就不必在嵌套的 if-else 案例中跟蹤 if-else。

讓我用一個例子來詳細說明。

public boolean function() {
    if (conditionA) {
        # Do something 1
    } else {
        # Do Something 2
    }

    return true/false;
}

// Different way You could write the code like this. 
// This will way cleaner and understandable 
// Than the previous version when there nested if-else.

public boolean function() {
    if (conditionA) {
        # Do something 1
        return true;
    } // Exit First 

    # Do Something 2
    return false;
}

為單個 if-else 尋找 Naive,但在巨大的嵌套 if-else 代碼中會有很大幫助。

但是,如果可以,請遵循一個良好的編碼原則。

暫無
暫無

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

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