Inserção de um nó no início de uma lista vinculada
No exercício anterior, você aprendeu a implementar uma classe Node() e LinkedList().
Neste exercício, você preparará o código do método insert_at_beginning() para adicionar um novo nó no início de uma lista vinculada.
Lembre-se da classe Node():
class Node:
def __init__(self, data):
self.data = data
self.next = None
Este exercício faz parte do curso
Estruturas de dados e algoritmos em Python
Instruções do exercício
- Crie o novo nó.
- Verificar se a lista vinculada tem um nó
head. - Se a lista vinculada tiver um nó
head, aponte o nónextdo novo nó parahead.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
def insert_at_beginning(self, data):
# Create the new node
new_node = ____(data)
# Check whether the linked list has a head node
if self.____:
# Point the next node of the new node to the head
new_node.___ = self.____
self.head = new_node
else:
self.tail = new_node
self.head = new_node