remove a node from the end of a linked list in python

To remove a node from the end of a linked list in python, we need to traverse the list till the second last node, and set its next pointer to None.

Here's an implementation:

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

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

    def remove_end(self):
        if self.head is None:
            return

        # If there is only one node in the list
        if self.head.next is None:
            self.head = None
            return

        # Traverse till the second last node
        second_last = self.head
        while second_last.next.next is not None:
            second_last = second_last.next

        # Set the next pointer of second last node as None
        second_last.next = None

    def print_list(self):
        temp = self.head
        while temp:
            print(temp.data, end=' ')
            temp = temp.next

# Example usage
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)

llist.head.next = second
second.next = third

print("Original List")
llist.print_list()

llist.remove_end()

print("\nList after removing end node")
llist.print_list()
1030 chars
49 lines

This will output:

main.py
Original List
1 2 3 
List after removing end node
1 2 
55 chars
5 lines

gistlibby LogSnag