+ 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
11 Respostas
+ 1
Izaiah Kay ,
Yeah. Update head inside loop. (No pun intended.)
https://sololearn.com/compiler-playground/ctFdIvFNzcOF/?ref=app
+ 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.
+ 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.
+ 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?
+ 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
+ 1
Rain ohhđ
, sorry i didnt get it at first.
First check this one out and see
https://code.sololearn.com/cWh97u17c64E/?ref=app
+ 1
Rain I see, looked through it but đ
head is boiling now. Any ideas ?
0
Izaiah Kay ,
With only current and next, I believe that would support a linked list, not a doubly linked list.
0
Rain exactly, thats why i need help to modify it or rewrite it if need be
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).
0
Izaiah Kay ,
Getting fun. I tested it. It currently fails at line 22.
https://sololearn.com/compiler-playground/ciUtz6W4nrP1/?ref=app