2.2.2. ALGORITHMS & DATASTRUCTURES. LINKED LISTS. ANOTHER VARIANT OF OPTIMIZING THE APPEND METHOD. TIME COMPLEXITY O(1).

The algorithm in the last article every time we insert a new element, the algorithm iterates through all the cells of the list until it reaches the last one. Then the algorithm links the last element with the new one. The complexity of such traversal will always be O(n). Without an early ending option. However, we can modify the code so that it runs in constant time O(1). For this, we should create another pointer that will link to the last element self.tail = None. Now, every time we add a new cell, we just need to access the tail attribute and return the last element. Next, we need to create a link from this element to the new one and then update the tail. As we don't have to iterate through all the cells, the insertion will work instantly.

class Node:
    def __init__(self, value=None, next_node=None):
        self.value = value
        self.next_node = next_node

    def __str__(self):
        return str(self.value)

class List:
    def __init__(self):
        # limiter
        self.top = Node()
        self.tail = None

    def append(self, value):
        '''
        Adding a new element to the end of a linked list.
        Operating time O(n).
        '''

        # Iterating through all elements sequentially to find the last one
        current = self.top
        while current.next_node is not None:
            current = current.next_node

        # Creating a reference for the last element to the new one
        current.next_node = Node(value)

    def __str__(self):
        '''
        Returns all elements of the linked list as a string
        '''
        current = self.top.next_node
        values = "["
        while current is not None:
            end = ", " if current.next_node else ""
            values += str(current) + end
            current = current.next_node

        return values + "]"

lst = List()
lst.append(75)
lst.append(12)
lst.append(28)
lst.append(6)
print(lst)        

要查看或添加评论,请登录

Igor Balitskyi的更多文章

  • ??? PDF to DOCX Conversion using Python

    ??? PDF to DOCX Conversion using Python

    ?? Libraries and Tools: pdfplumber, python-docx. pdfplumber: Used for opening and processing PDF files.

  • PROTECTING AN SSH SERVER, PORT KNOCKING

    PROTECTING AN SSH SERVER, PORT KNOCKING

    In this article, I will discuss methods for securing an SSH server, which we use to connect to and control remote…

  • HTTP, HTTP2, HTTPS

    HTTP, HTTP2, HTTPS

    After a user enters a website address in the browser, a request is first formed, which is then sent through a network…

  • SORTING LINKED LISTS. PART 1.

    SORTING LINKED LISTS. PART 1.

    Often, there is a need to get values from linked lists in ascending or descending order, and for this purpose, there…

    1 条评论
  • Первый язык программирования

    Первый язык программирования

    Можно ли считать Паскаль коммерчески успешным языком с точки зрения начинающего программиста? Сравним Паскаль и Питон…

    1 条评论
  • ?? How to solve problems that seem unsolvable

    ?? How to solve problems that seem unsolvable

    Sometimes, programmers face complex algorithmic problems with no obvious solutions. In these situations, they have to…

    1 条评论
  • 2.3. ALGORITHMS & DATA STRUCTURES. DOUBLY LINKED LISTS.

    2.3. ALGORITHMS & DATA STRUCTURES. DOUBLY LINKED LISTS.

    Doubly linked lists differ from singly linked lists in that each node refers to both the next and previous nodes…

  • 2.2.3. ALGORITHMS & DATA STRUCTURES. LINKED LISTS. THE DELETE METHOD.

    2.2.3. ALGORITHMS & DATA STRUCTURES. LINKED LISTS. THE DELETE METHOD.

    In this method, we need to do two things. First, we need to find a cell with the specified value, and second, we need…

  • 2.2. ALGORITHMS & DATASTRUCTURES. LINKED LISTS - OPTIMIZATION.

    2.2. ALGORITHMS & DATASTRUCTURES. LINKED LISTS - OPTIMIZATION.

    В последней статье мы рассмотрели связный список, у которого был метод append для добавления новых элементов в конец…

  • РАЗДЕЛ 2. SECTION 2. СТРУКТУРЫ ДАННЫХ. DATA STRUCTURES. СВЯЗНЫЕ СПИСКИ, LINKED LISTS

    РАЗДЕЛ 2. SECTION 2. СТРУКТУРЫ ДАННЫХ. DATA STRUCTURES. СВЯЗНЫЕ СПИСКИ, LINKED LISTS

    Структура данных — это контейнер для организации, хранения и обработки информации. A data structure is a container for…

社区洞察

其他会员也浏览了