繁体   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