+ 3

Linked list reverse

How can this code be best modified to reverse a doubly linked list while ensuring that both “next”and “prev” pointers are appropriately updated during the reversal process. https://code.sololearn.com/ckORoit1CZJU/?ref=app

14th Jan 2024, 4:36 AM
Izaiah Kay
Izaiah Kay - avatar
11 Antworten
+ 1
Izaiah Kay , Yeah. Update head inside loop. (No pun intended.) https://sololearn.com/compiler-playground/ctFdIvFNzcOF/?ref=app
16th Jan 2024, 9:27 AM
Rain
Rain - avatar
+ 2
I don't understand your code at line 13 14 15 why you doing it "current.next = prev" And prev = current I think you may rewrite your code with code scheme.
14th Jan 2024, 6:22 AM
Muhammadrizo
Muhammadrizo - avatar
+ 2
Muhammadrizo next_node = current.next Saves the next node in the original list before the reversal. current.next = prev Adjusts the next pointer of the current node to point to the previous node, reversing the direction. prev = current: Moves the prev pointer to the current node for the next iteration. current = next_node: Moves the current pointer to the next node in the original list for the next iteration.
14th Jan 2024, 6:39 AM
Izaiah Kay
Izaiah Kay - avatar
+ 1
Izaiah Kay , If I wanted to reverse a doubly linked list, I would swap previous and next for each member in the list. Python makes it easy to swap the values of two variables without creating any new variables. a, b = 5, 10 a, b = b, a print(a, b) # 10, 5 Why doesn't your class Node have a prev attribute?
14th Jan 2024, 9:05 PM
Rain
Rain - avatar
+ 1
Rain because initially The prev variable is used to keep track of the previous node as you traverse the list and reverse the next pointers assigning it in later stages
15th Jan 2024, 4:19 PM
Izaiah Kay
Izaiah Kay - avatar
+ 1
Rain ohh😅, sorry i didnt get it at first. First check this one out and see https://code.sololearn.com/cWh97u17c64E/?ref=app
16th Jan 2024, 3:42 AM
Izaiah Kay
Izaiah Kay - avatar
+ 1
Rain I see, looked through it but 😅 head is boiling now. Any ideas ?
16th Jan 2024, 8:38 AM
Izaiah Kay
Izaiah Kay - avatar
0
Izaiah Kay , With only current and next, I believe that would support a linked list, not a doubly linked list.
15th Jan 2024, 6:24 PM
Rain
Rain - avatar
0
Rain exactly, thats why i need help to modify it or rewrite it if need be
15th Jan 2024, 7:19 PM
Izaiah Kay
Izaiah Kay - avatar
0
Izaiah Kay , Heh. We just went in a circle. My advice is to add a previous attribute to your Node class as a first step. Then you'll be able to create objects capable of assembling into a doubly linked list (which you'll need before you can reverse it).
15th Jan 2024, 10:00 PM
Rain
Rain - avatar
0
Izaiah Kay , Getting fun. I tested it. It currently fails at line 22. https://sololearn.com/compiler-playground/ciUtz6W4nrP1/?ref=app
16th Jan 2024, 8:26 AM
Rain
Rain - avatar