Python Forum
Deleting the first item in linked list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Deleting the first item in linked list (/thread-16569.html)



Deleting the first item in linked list - dan789 - Mar-05-2019

Hello, this is what I have so far:

class Linked_list:
    def __init__(self, data, next=None):
        self.data, self.next = data, next

def print_list(list):
    while list is not None:
        print(list.data, end=' ---> ')
        list = list.next
    print(None)

def make(sequence):
    list = None
    for value in reversed(sequence):
        list = Linked_list(value, list)
    return list

def remove_first(list):
    ...
I simply donĀ“t know how to delete the first item of my linked list. I should use just structure I wrote above. Can you give me a help?

Thanks.


RE: Deleting the first item in linked list - ichabod801 - Mar-05-2019

Using list as a variable name is a bad idea. list is a built-in, and by using it as a variable name, you block the use of the built-in, which could cause errors in other code.

Let's say your linked list is called llist. llist is actually the first item in you list, and it links to the next item in the list. The second item in the list is llist.next. Can you see then how to make the first item in your list be the second item in your list, thus deleting the previous first item?


RE: Deleting the first item in linked list - dan789 - Mar-05-2019

I could change a refference to the second item? But not sure how to do this using a separate function remove_first.


RE: Deleting the first item in linked list - ichabod801 - Mar-05-2019

If remove_first is not supposed to have a return value, you could copy the values of the second item in the list into the first item of the list.


RE: Deleting the first item in linked list - dan789 - Mar-05-2019

Something like this?

llist.data = llist.next.data


RE: Deleting the first item in linked list - ichabod801 - Mar-05-2019

That's half of it.


RE: Deleting the first item in linked list - dan789 - Mar-05-2019

llist.next = llist.next.next works at least in my case. Is it correct?


RE: Deleting the first item in linked list - ichabod801 - Mar-05-2019

Yeah, that's the other half.