Inserting a node at the beginning of a linked list
In the previous exercise, you learned how to implement a Node() and LinkedList() class.
In this exercise, you will prepare the code for the insert_at_beginning() method to add a new node at the beginning of a linked list.
Recall the Node() class:
class Node:
def __init__(self, data):
self.data = data
self.next = None
Bu egzersiz
Data Structures and Algorithms in Python
kursunun bir parçasıdırEgzersiz talimatları
- Create the new node.
- Check whether the linked list has a
headnode. - If the linked list has a
headnode, point thenextnode of the new node to thehead.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
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