Get a free weekly practice problem!

Keep that axe sharp.

× No thanks

Just No more free questions left!

Upgrade Now

Hooray! It's opposite day. Linked lists go the opposite way today.

Write a method for reversing a linked list. Do it in-place.

Your method will have one input: the head of the list.

Your method should return the new head of the list.

Here's a sample linked list node class:

public static class LinkedListNode { public int value; public LinkedListNode next; public LinkedListNode(int value) { this.value = value; } }

We can do this in space. So don't make a new list; use the existing list nodes!

We can do this is in time.

Careful—even the right approach will fail if done in the wrong order.

Try drawing a picture of a small linked list and running your method by hand. Does it actually work?

The most obvious edge cases are:

  1. the list has 0 elements
  2. the list has 1 element

Does your method correctly handle those cases?

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

time and space. We pass over the list only once, and maintain a constant number of variables in memory.

This in-place reversal destroys the input linked list. What if we wanted to keep a copy of the original linked list? Write a method for reversing a linked list out-of-place.

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

What's next?

Powered by qualified.io

. . .