【问题标题】:Insert at head in python linked list在python链表的头部插入
【发布时间】:2020-12-30 19:02:08
【问题描述】:

我正在使用 Python 在链表的头部实现插入。我引用了这个guide。对于案例 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')

【问题讨论】:

  • 嗯,你当然不需要回头,只需要return。您只需要在此时结束函数,否则您将继续处理案例 3。您可以将案例 3 轻松包装在 else 中,但我认为 return 更可爱。
  • 谢谢,这是有道理的。我认为这只是我引用的链接中的一个错字。

标签: python algorithm data-structures linked-list


【解决方案1】:
  • 功能的实现取决于您。可以更改。
  • 关于他为什么使用 return 是为了输出函数或者其他任何步骤#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 看起来很朴素,但在巨大的嵌套 if-else 代码中会有很大帮助。

但要尽可能遵循良好的编码原则。

【讨论】:

    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2020-06-28
    • 2021-03-24
    • 2013-09-12
    相关资源
    最近更新 更多