Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete function in LinkedList.py not working #52

Open
bharathikannann opened this issue Jun 8, 2021 · 1 comment
Open

Delete function in LinkedList.py not working #52

bharathikannann opened this issue Jun 8, 2021 · 1 comment

Comments

@bharathikannann
Copy link

bharathikannann commented Jun 8, 2021

@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
@rohanrkamath
Copy link

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants