DEV Community

Hariprasath
Hariprasath

Posted on • Edited on

Finally realized how reverse list work

the core is prev pointer is storing the current

while(current){
next = current.next
current.next = prev
prev = current
current = next
}

let discuss the part

[0,1,2,3,4]

**prev = null
current = {data:0,next:1}
next = null**

saving current.next in next (later use)

current = {data:0,next:1}
current.next contains {data:1,next:2}
current.next = prev {null}

now current modified {data:0,next:1} to {data:0,next:null}

prev = current so prev is null to {data:0,next:null}

current = next // now next stores the {data:1,next:2}
Enter fullscreen mode Exit fullscreen mode

// next iteration

current = {data:1,next:2}
next = current.next {data:2,next:3}

current.next = prev {data:0,next:null}

now current has {data:1,next:{data:0,next:null}}

prev = current
//{data:0,next:null} to {data:1,next:{data:0,next:null}}

current = next {data:2,next:3}
Enter fullscreen mode Exit fullscreen mode

//third iteration

current = {data:2,next:3}
next = current.next {data:3,next:4}

current.next = prev {data:1,next:{data:0,next:null}}

current has {data:2,next:{data:1,next:{data:0,next:null}}

prev = current
{data:1,next:{data:0,next:null}} to {data:2,next:{data:1,next:{data:0,next:null}}

current = next
Enter fullscreen mode Exit fullscreen mode

{data:3,next:4}

//fourth iteration

current = {data:3,next:4}
next = current.next {data:4,next:null}

current.next = prev {data:2,next:{data:1,next:{data:0,next:null}}

current has {data:3,next:{data:2,next:{data:1,next:{data:0,next:null}}}

prev = current
{data:2,next:{data:1,next:{data:0,next:null}} to {data:3,next:{data:2,next:{data:1,next:{data:0,next:null}}}

current = next
Enter fullscreen mode Exit fullscreen mode

{data:4,next:null}

//last iteration

current = {data:4,next:null}
next = current.next {null}

current.next = prev {data:3,next:{data:2,next:{data:1,next:{data:0,next:null}}}

current become {data:4,next:{data:3,next:{data:2,next:{data:1,next:{data:0,next:null}}}}

prev = current

current = next
Enter fullscreen mode Exit fullscreen mode

completed
happy great coding

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay