Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Not Able To Delete First Node From Python Linked List
#1
I have a linked list in python that I am presently implementing. However the scenario of deleting the first node isnt working for me.

Deleting the node at any other point in the list works fine.

I have searched youtube tutorials and other online posts but it seems to have the exact same lines of code that I have.

I have also tried putting print statements in before the lines - self.head = HeadVal.nextval - HeadVal = None

From the output, it does seem to pass the headnode onto the second element of the list and clear the original first item, but when I print the list again the original first node hasnt been deleted. Its almost like the new list structure hasnt been committed to memory if that makes sense?

class Node: 
            def init(self, dataval): 
                    self.dataval = dataval 
                    self.nextval = None

class LinkedList: 
            def init(self): 
                     self.headval = None


            def listprint(self):
                      printval = self.headval

                      while printval is not None:
                           print (printval.dataval)
                           printval = printval.nextval

             def removeNode(self):

                       nodeToRemove = input("Enter Node To Remove: ")
                       HeadVal = self.headval

                       if (HeadVal is not None):
                         if (HeadVal.dataval == nodeToRemove):
                             self.head = HeadVal.nextval
                             HeadVal = None
                             return
                         else:
                              while (HeadVal is not None):
                                 if HeadVal.dataval == nodeToRemove:
                                 break
                                 prev = HeadVal
                                 HeadVal = HeadVal.nextval

                         prev.nextval = HeadVal.nextval
                         HeadVal = None
                    else:
                         print("Nothing To Delete")




def MainMenu():

print("1. Create A Linked List")
print("2. Delete A Linked List")
print("3. Check If A Linked List Is Empty")
print("4. Print Out The Values In The List")
print("5. Find A Node In A Linked List")
print("6. Insert A Node In A Linked List")
print("7. Delete A Node In A Linked List")
print("99. Exit")

anotherOption = True

while anotherOption == True:

    print("")
    selection=int(input("Main Menu --- Enter Choice: "))

    if selection==1:    
        myList = LinkedList()
        myList.init()
        print("Linked List Created")

    elif selection==6:
        print("")
        print("A. Insert A Node Into The Front Of The Linked List")
        print("B. Insert A Node Into The End Of The Linked List")       
        print("")
        entrySelection=input("Enter Insert Node Choice: ")

        if entrySelection in ["A", "a"]:
            myList.insertAtBegining()
        elif entrySelection in ["B", "b"]:
            myList.insertAtEnd()

        else:
            print("")
            print("Enter A Valid Selection For Inserting Node")



    elif selection==4:
        myList.listprint()


    elif selection==7:
        myList.removeNode()

    elif selection==99:
        anotherOption = False
        print("")
        print("Exiting Main Menu")

    else:
        print("")
        print("Enter A Valid Selection On Main Menu")

MainMenu()
Quote
#2
I've code tags to your code but the indentation need some attention.
Quote
#3
Hi Yoriz,

Thanks for your reply. Yes I lost some of the indentation when I copied and pasted, but the indentation isnt causing any problems when I run it.

Its the lines 24-27 that I am specifically looking at. Am I missing a line of code that commits the list to its new status?
Quote
#4
IF the indentation is correct, that seems right to me. Can you show us the code with the correct indentation, and with the insertion methods? Just the class, not the menu interface.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#5
class Node:
    def init(self, dataval):
        self.dataval = dataval
        self.nextval = None


class LinkedList:


    def init(self):
        self.headval = None
        

    def listprint(self):
        
        printval = self.headval
        
        while printval is not None:
            print (printval.dataval)
            printval = printval.nextval
        
            
    def insertAtBegining(self):
        
        nodeToPutAtStart = input("Enter Node To Put At The Start: ")
        
        startNode = Node()
        startNode.init(nodeToPutAtStart)
        
        
        startNode.nextval = self.headval
        self.headval = startNode
        
        print(nodeToPutAtStart, " Has Been Added To The Start Of The Linked List")

        
    def insertAtEnd(self):

        nodeToPutOnEnd = input("Enter Node To Put On The End: ")
        
        endNode = Node()
        endNode.init(nodeToPutOnEnd)
        
        if self.headval is None:
            self.headval = endNode
            return
        
        laste = self.headval
        
        while(laste.nextval):
            laste = laste.nextval
        
        laste.nextval=endNode
        
        print(nodeToPutOnEnd, " Has Been Added To The End Of The Linked List")
        
        
    def insertInbetween(self):
        
        middleNodeUserInput = input("Enter Middle Node: ")
        nodeToAddUserInput = input("Enter New Note To Add: ")
            
        middleNode = Node()
        middleNode.init(middleNodeUserInput)

        nodeToAdd = Node()
        nodeToAdd.init(nodeToAddUserInput)
        
        nodeToAdd.nextval = middleNode.nextval
        middleNode.nextval = nodeToAdd
        
        
        
    def removeNode(self):
	    
	    nodeToRemove = input("Enter Node To Remove: ")
	    HeadVal = self.headval
	    
	    if (HeadVal is not None):
	        if (HeadVal.dataval == nodeToRemove):

	            return
	        else:
        	    while (HeadVal is not None):
        	       if HeadVal.dataval == nodeToRemove:
        	           self.head = HeadVal.nextval
        	           HeadVal = None
        	           break
        	       prev = HeadVal
        	       HeadVal = HeadVal.nextval
        	       
        	    prev.nextval = HeadVal.nextval
	            HeadVal = None
	    else:
	        print("Nothing To Delete")
    
    
    def isEmpty(self):
        HeadVal = self.headval
        total = 0
        
        while (HeadVal is not None):
            total+=1
            HeadVal = HeadVal.nextval

        if(total == 0):
            print("List Is Empty")
        else:
            print("List Is Not Empty")
            
        print(total, " Elements In List")
Yoriz wrote Mar-04-2019, 09:06 PM:
Please add python code tags to future posts
Quote
#6
Please use python and output tags when posting code and results. Yoriz has done it for you twice. Here are instructions for doing it yourself next time.

The problem is that you are setting HeadVal to None when it matches the node to remove. I think you have your code for removing the head of the list mixed up with the code for removing a non-head node.

I would also note that you should be using __init__ instead of init. The former is done automatically on object creation, and would simplify your code (and remove a source of potential errors). I would also look at __repr__, it is your friend when debugging.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#7
Hi Folks,

Apologies. I accidentally cut the code of how Im deleting the first node.

Thanks ichabod801, I take your point about __init__ but is that likely to be a factor in this instance?


class Node:
    def init(self, dataval):
        self.dataval = dataval
        self.nextval = None

class LinkedList:
    def init(self):
        self.headval = None
        

    def listprint(self):
        
        printval = self.headval
        
        while printval is not None:
            print (printval.dataval)
            printval = printval.nextval
        
            
    def insertAtBegining(self):
        
        nodeToPutAtStart = input("Enter Node To Put At The Start: ")
        
        startNode = Node()
        startNode.init(nodeToPutAtStart)
        
        
        startNode.nextval = self.headval
        self.headval = startNode
        
        print(nodeToPutAtStart, " Has Been Added To The Start Of The Linked List")


        
        
        
    def insertAtEnd(self):

        nodeToPutOnEnd = input("Enter Node To Put On The End: ")
        
        endNode = Node()
        endNode.init(nodeToPutOnEnd)
        
        if self.headval is None:
            self.headval = endNode
            return
        
        laste = self.headval
        
        while(laste.nextval):
            laste = laste.nextval
        
        laste.nextval=endNode
        
        print(nodeToPutOnEnd, " Has Been Added To The End Of The Linked List")
        
        
        
        
        
        
        
        
    def insertInbetween(self):
        
        middleNodeUserInput = input("Enter Middle Node: ")
        nodeToAddUserInput = input("Enter New Note To Add: ")
            
        middleNode = Node()
        middleNode.init(middleNodeUserInput)

        nodeToAdd = Node()
        nodeToAdd.init(nodeToAddUserInput)
        
        nodeToAdd.nextval = middleNode.nextval
        middleNode.nextval = nodeToAdd
        
        
        
    def removeNode(self):
	    
	    nodeToRemove = input("Enter Node To Remove: ")
	    HeadVal = self.headval
	    
	    if (HeadVal is not None):
	        if (HeadVal.dataval == nodeToRemove):
	            self.head = HeadVal.nextval
	            HeadVal = None
	            return
	        else:
        	    while (HeadVal is not None):
        	       if HeadVal.dataval == nodeToRemove:
        	           self.head = HeadVal.nextval
        	           HeadVal = None
        	           break
        	       prev = HeadVal
        	       HeadVal = HeadVal.nextval
        	       
        	    prev.nextval = HeadVal.nextval
	            HeadVal = None
	    else:
	        print("Nothing To Delete")
    
    
    
    
    
    def isEmpty(self):
        HeadVal = self.headval
        total = 0
        
        while (HeadVal is not None):
            total+=1
            HeadVal = HeadVal.nextval

        if(total == 0):
            print("List Is Empty")
        else:
            print("List Is Not Empty")
            
        print(total, " Elements In List")











def MainMenu():


	print("1. Create A Linked List")
	print("2. Delete A Linked List")
	print("3. Check If A Linked List Is Empty")
	print("4. Print Out The Values In The List")
	print("5. Find A Node In A Linked List")
	print("6. Insert A Node In A Linked List")
	print("7. Delete A Node In A Linked List")
	print("99. Exit")
	
	anotherOption = True
	
	while anotherOption == True:
		
		print("")
		selection=int(input("Main Menu --- Enter Choice: "))
		
		if selection==1:	
			myList = LinkedList()
			myList.init()
			print("Linked List Created")
			
		elif selection==6:
		    print("")
		    print("A. Insert A Node Into The Front Of The Linked List")
		    print("B. Insert A Node Into The End Of The Linked List")
		    print("C. Insert A Node In Between Nodes On The Linked List")
		    
		    print("")
		    entrySelection=input("Enter Insert Node Choice: ")
		    
		    if entrySelection in ["A", "a"]:
    			myList.insertAtBegining()
		    elif entrySelection in ["B", "b"]:
		        myList.insertAtEnd()
                
		    elif entrySelection in ["C", "c"]:
		        myList.insertInbetween()

		    else:
		        print("")
		        print("Enter A Valid Selection For Inserting Node")
		
		
		
		elif selection==4:
		    myList.listprint()
		    
		
		elif selection==7:
		    myList.removeNode()
    	
		elif selection==99:
			anotherOption = False
			print("")
			print("Exiting Main Menu")
			
		elif selection==3:
		    myList.isEmpty()	
					
			
		else:
		    print("")
		    print("Enter A Valid Selection On Main Menu")
			
MainMenu()

Quote
#8
So basically its lines 86 - 89 that aernt working correctly for me.

So when I have my linked list of the following values
50 --- 60 --- 70 --- 80 --- 90

I can delete any of the values apart from the head.

Does my code need another line to commit the deletion of the head to memory? From my testing, it does seem to delete the head node and re assign it to the second node, but when I do a print list, its like it "Rolls Back" to its previous state.
Quote
#9
When you delete the head node, you are setting self.head, not self.headval.

(Mar-04-2019, 09:38 PM)ribena1980 Wrote: Thanks ichabod801, I take your point about __init__ but is that likely to be a factor in this instance?

Not a problem in this case, just general programming critique. The other thing I forgot to mention is that you are mixing your interface and your data, which is a good thing to avoid. That is, your list is asking the user questions. That means that you can't create a list without a user. So when you insert a value, the insertFoo methods should take the value as a parameter. The interface should be where the user is asked for a value, and the interface should pass the value to the method.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  delete a file after closing it mcgrim 1 157 May-14-2019, 08:16 PM
Last Post: Larz60+
  circle node with horizontal line in python graphviz mandana 0 163 May-05-2019, 10:39 AM
Last Post: mandana
  Object type of Node to json bhojendra 4 318 Apr-28-2019, 01:36 PM
Last Post: bhojendra
  How to list number of times element is in defaultdict and delete it mrapple2020 3 225 Apr-15-2019, 07:34 AM
Last Post: perfringo
  Why doesn't gc delete an object without forcing a garbage collection call? AlekseyPython 5 429 Mar-19-2019, 02:10 AM
Last Post: micseydel
  Deleting the first item in linked list dan789 7 391 Mar-05-2019, 06:34 PM
Last Post: ichabod801
  How to get a random item from a list, print it and delete it? giorgosmarga 3 314 Feb-22-2019, 05:33 PM
Last Post: Yoriz
  Send The output of Gyroscope sensor to node red jenkins43 1 227 Feb-07-2019, 11:00 AM
Last Post: Larz60+
  Delete multiple files using file extention sumncguy 2 356 Jan-23-2019, 03:05 AM
Last Post: snippsat
  xml element inside text node SgtPembry 9 495 Oct-21-2018, 11:07 PM
Last Post: SgtPembry

Forum Jump:


Users browsing this thread: 1 Guest(s)