简体   繁体   中英

Insert at head in python linked list

I'm implementing inserting at a linked list's head using 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. 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. 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.
  • 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. (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.

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.

But a Good Coding principle to follow when you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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