add a node to the beginning of a linked list in python

To insert a new node at the beginning of a linked list, you can follow these steps:

  1. Create a new node with the data you want to insert.
  2. Set the next attribute of the new node to the current head of the linked list.
  3. Set the head of the linked list to be the new node.

Here's an implementation in Python:

main.py
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        
class LinkedList:
    def __init__(self):
        self.head = None
        
    def push(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node
296 chars
14 lines

In this implementation, we define a Node class to represent a single node in the linked list, and a LinkedList class to hold the head of the list and provide methods for operating on it. The push method takes a data parameter and inserts a new node with that data at the beginning of the list.

gistlibby LogSnag