[Python] Deleting a Linked List and printing it (GeeksForGeeks)

Discussão em 'Python' iniciado por Stack, Junho 23, 2025.

  1. Stack

    Stack Membro Participativo

    My code:

    class Node():
    # defining attributes of node and constructor
    def __init__(self,data):
    self.data = data
    self.next = None

    class LinkedList():
    # defining the attribute
    def __init__(self):
    self.head = None

    def printList(self):
    if self.head is None:
    print("The LinkList is empty")
    else:
    temp1 = self.head
    while(temp1):
    print(temp1.data)
    temp1 = temp1.next

    def deleteLinkedList(self):
    if self.head is None:
    print("The LinkedList is already empty")
    else:
    temp2 = self.head
    while(temp2.next!=None):
    current = temp2
    temp2 = temp2.next
    del current.data
    self.head = None


    My doubt:

    Is this code correct to delete a while link list?

    Why am I setting self.head to None after deleting the linked list?

    Because I want to print the content of the list using the following function:

    def printList(self):
    if self.head is None:
    print("The LinkList is empty")
    else:
    temp1 = self.head
    while(temp1):
    print(temp1.data)
    temp1 = temp1.next

    Continue reading...

Compartilhe esta Página