0

Pls explain this code to me

class node: def __init__(self, data = None, next = None): self.data = data self.next = next class linked_list: def __init__(self): self.head = None # function to add a node at front def add_at_front(self, data): self.head = node(data=data, next=self.head) # function to check whether the list is empty def is_empty(self): return self.head == None # function to add node at the end def add_at_end(self, data): if not self.head: self.head = node(data=data) return curr = self.head while curr.next: curr = curr.next curr.next = node(data=data) # function to delete any node def delete_node(self, key): curr = self.head prev = None while curr and curr.data != key: prev = curr curr = curr.next if prev is None: self.head = curr.next elif curr: prev.next = curr.next

18th Jul 2020, 9:15 AM
Shafayet Arish
Shafayet Arish - avatar
10 odpowiedzi
+ 3
what are you having trouble understanding?
18th Jul 2020, 9:17 AM
Slick
Slick - avatar
+ 3
That method places a new node instance in the first spot (not the last one like usual.) Then it makes the first node(from before) become the 2nd node in line when connected to the new node. Does this make sense? 2-3-4-5 Then if I add 1 at front 1-2-3-4-5
18th Jul 2020, 9:23 AM
Slick
Slick - avatar
0
The add_at_front method
18th Jul 2020, 9:19 AM
Shafayet Arish
Shafayet Arish - avatar
0
Can you give me any other kind of example referring to this code: self.head = node(data=data, next=self.head)
18th Jul 2020, 10:14 AM
Shafayet Arish
Shafayet Arish - avatar
0
i have a linked list, lets call it lett_ls: b-c-d-e it has an attribute called .head lett_ls.head.data == 'b' the above statement is true. the first thing add_to_front() does is make a new instance of a node. It then loads up with data and assigns the previous head to be the new nodes next attribute(the linking of linked lists). lets lett_ls.add_to_front('a')... a-b-c-d-e
18th Jul 2020, 10:22 AM
Slick
Slick - avatar
0
Well in your linked list "b-c-d-e" which one is node?
18th Jul 2020, 10:25 AM
Shafayet Arish
Shafayet Arish - avatar
0
what you see is a representation of it. Its all the data of the nodes "linked" by - characters. Its for visual
18th Jul 2020, 10:26 AM
Slick
Slick - avatar
0
Its all in your head, just depends on how you see it. Thats how i like to picture linked lists
18th Jul 2020, 10:28 AM
Slick
Slick - avatar
0
Will you explain me the add_at_end and delete_node methods
20th Jul 2020, 1:05 PM
Shafayet Arish
Shafayet Arish - avatar
0
yeah shoot me a message with the code and id be more than happy to
20th Jul 2020, 1:06 PM
Slick
Slick - avatar