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

To add a new node to the end of a linked list in Python, you can follow these steps:

  1. Create a new node with the data you want to add.
  2. Traverse the linked list until you reach the last node.
  3. Set the next pointer of the last node to point to the new node.
  4. Set the next pointer of the new node to None.

Here's the Python code to implement this:

main.py
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def add_node(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return

        last_node = self.head
        while last_node.next is not None:
            last_node = last_node.next

        last_node.next = new_node
        new_node.next = None
479 chars
22 lines

In this code, we define two classes Node and LinkedList. Node represents a single node in the linked list and LinkedList represents the entire linked list. The add_node method of the LinkedList class adds a new node to the end of the list, as described above.

gistlibby LogSnag