brazerzkidailens.blogg.se

Reverse linked list
Reverse linked list









reverse linked list

Ideally, we can insert an element into a linked list either at the head or at the tail. def print_lst(head):Ĭreating a linked list: # Initialize the linked list object Let’s also define a print_lst function to visualize the contents of a given linked list.

#Reverse linked list code

Now that we have the code ready, let’s create a linked list. This is just one implementation among them. There are multiple ways to get the head of the linked list. We also have a method to get the head of the linked list. We insert the new node to the variable and assign the new node to self.current. The reason is, we keep track of the last inserted node in the self.current variable. The time complexity of inserting a node in this code is O(1). I will tell you the reason why we are doing so when we reverse the linked list. In the above code, we insert the elements at the tail of the linked list. The LinkedList class is where all the nodes are initialized and inserted either at the head/tail of a linked list based on the requirement. In the above example, 10, 20,30 and 40 are stored in the data variable. The data attribute holds the node data value and the next stores the successive node object. # Insertion for non head elements using current object The insertion here is performed with a time complexity of O(1) # We have a current value to always point to the last node Reverse the singly linked list, provided the head node is available.The output should be as below 40->30->20->10 Our linked list here has the following elements 10->20->30->40

reverse linked list

Let’s assume we have a linked list like above Given a singly linked list, reverse it without using additional data structures.











Reverse linked list