Data-Structures-using-Python icon indicating copy to clipboard operation
Data-Structures-using-Python copied to clipboard

Delete function in LinkedList.py not working

Open bharathikannann opened this issue 4 years ago • 1 comments

@OmkarPathak, In the delete method in linkedlist.py the last element will be deleted if the given key is not present and if only the head node is present then there will a reference error for prev node.

So I have made some changes and it works

# deleting an item based on data(or key)
def delete(self, data):
    temp = self.head
    # if data/key is found in head node itself
    if(temp.data == data):
            self.head = temp.next
            temp = None
            return
        else:
            #  else search all the nodes
            while(temp.next):
                if(temp.data == data):
                    break
                prev = temp          #save current node as previous so that we can go on to next node
                temp = temp.next
            
            # node not found
            if temp == None:
                return
            
            prev.next = temp.next
            return

bharathikannann avatar Jun 08 '21 05:06 bharathikannann

@bharathikannann Yep, there is an error in @OmkarPathak's code. Yours works fine, but check mine out, I feel your code has some steps that can be skipped. It's in my DSA-stuff repo.

	def removeAtData(self, data):
		
		if self.head and self.head.data == data:
			self.head = self.head.next
			return

		temp = self.head

		prev = None

		while temp and temp.data != data:
			prev = temp
			temp = temp.next

			if temp is None:
				print('The element is not in the list.')
				return

		prev.next = temp.next

rohanrkamath avatar May 09 '22 06:05 rohanrkamath