简体   繁体   English

在 python 链表的头部插入

[英]Insert at head in python linked list

I'm implementing inserting at a linked list's head using Python.我正在使用 Python 在链表的头部实现插入。 I'm referencing this guide .我正在参考本指南 for case 2, I found I must add return self.head to get driver code to properly insert at head otherwise it will not terminate.对于案例 2,我发现我必须添加return self.head以使驱动程序代码正确插入头部,否则它不会终止。 Why is that?这是为什么? I would consider the first lines to be enough since I'm calling this method to modify the linked list in place.我认为第一行就足够了,因为我正在调用此方法来修改链表。 why do i need to return?为什么我需要返回?

And here is the code for insert before a node:这是在节点之前插入的代码:

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
        ...

driver code:驱动代码:

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')
  • The Implementation of the function depends upon you. function 的实现取决于您。 It can be changed.它可以改变。
  • And Regarding Why he used a return is to just come out the function or else whatever other steps are there #case3 they will run which is not expected.而关于他为什么使用回报是刚出来 function 或其他任何其他步骤#case3 他们将运行这是意料之外的。
  • Generally, When you write a code better than writing an if-else clause it would be better to use exit first or execute the remaining code.通常,当您编写代码比编写 if-else 子句时,最好先使用 exit 或执行剩余的代码。 (here exit is return statement). (这里退出是返回语句)。
    • This way of coding will be easy to understand for other developers who see code so that they don't have to track the if-else in nested if-else case.这种编码方式对于其他看到代码的开发人员来说很容易理解,这样他们就不必在嵌套的 if-else 案例中跟踪 if-else。

Let me elaborate it with an Example.让我用一个例子来详细说明。

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;
}

Look Naive for single if-else but will a great help in huge nested if-else codes.为单个 if-else 寻找 Naive,但在巨大的嵌套 if-else 代码中会有很大帮助。

But a Good Coding principle to follow when you can.但是,如果可以,请遵循一个良好的编码原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM