Python Challenge - Reverse a Singly-Linked List

This community-built FAQ covers the “Reverse a Singly-Linked List” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Reverse a Singly-Linked List

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

from LinkedList import *

def __iter__(self):
  node = Node(self).data
  while node:
    yield node.data
    node = node.next

def reverse_linked_list(linked_list):
  revList = None
  for i in __iter__(linked_list):
    revList = Node(i, revList)
  return revList

print("Original")
demo_list = make_linked_list([4,8,15])
demo_list.print_linked_list()
print("Reversed")
reverse = reverse_linked_list(demo_list)
reverse.print_linked_list()
print("Original Unchanged")
demo_list.print_linked_list()
from LinkedList import * def reverse_linked_list(linked_list): first_node = linked_list second_node = None while first_node != None: new_node = Node(first_node.data, second_node) second_node = new_node first_node = first_node.next return second_node demo_list = make_linked_list([4,8,15]) reverse = reverse_linked_list(demo_list)

Build the reversed list by iterating through the given linked list from first to last and prepending every node to the reversed list, pointing each node’s next pointer to the previously added node.

Has anyone done this challenge using recursion? (I did not.)

I added in checking if each node had a next attribute, otherwise I kept getting an error.
My solution is longer than the ones in the other posts.

My solution to the challenge
def reverse_linked_list(linked_list):
  current_node = linked_list
  if linked_list is None:
    return None
  if not hasattr(current_node, "next"):
    return Node(current_node.data)
  next_node = current_node.next
  reversed_node_list = []
  reversed_node = Node(current_node.data)
  reversed_node_list.append(reversed_node)

  while next_node is not None:
    reversed_node = Node(next_node.data, reversed_node)
    reversed_node_list.insert(0, reversed_node)
    current_node = next_node
    if not hasattr(current_node, "next"):
      break
    next_node = current_node.next

  return reversed_node

Here’s proof that it works:

class Node: def __init__(self, data, next_node=None): self.data = data self.next = next_node def __repr__(self): data = str(self.data) if self.next is None: return data + " -> None" elif hasattr(self.next, "data"): return data + " -> " + str(node.next.data) else: return data + " -> " + repr(node.next) def print_linked_list(self): print(self.data) current = self next = current.next while next is not None: print(next.data) current = next next = current.next def make_linked_list(list_of_data): node_list = [] current = None previous = None for item in list_of_data: current = Node(item) node_list.append(current) if previous is not None: previous.next = current previous = current if len(node_list) == 0: return None else: return node_list[0] def reverse_linked_list(linked_list): current_node = linked_list if linked_list is None: return None if not hasattr(current_node, "next"): return Node(current_node.data) next_node = current_node.next reversed_node_list = [] reversed_node = Node(current_node.data) reversed_node_list.append(reversed_node) while next_node is not None: reversed_node = Node(next_node.data, reversed_node) reversed_node_list.insert(0, reversed_node) current_node = next_node if not hasattr(current_node, "next"): break next_node = current_node.next return reversed_node def print_linked_list(head_node, between = " -> "): print(head_node.data, end = between ) current = head_node next = current.next while next is not None: print(next.data, end = between ) current = next next = current.next print("None") def data_iterator(head_node): # generator function current = head_node yield current.data while hasattr(current, "next") and current.next is not None: current = current.next yield current.data print("Original") demo_list = make_linked_list([4,8,15]) print_linked_list(demo_list) print("Reversed") reverse = reverse_linked_list(demo_list) print_linked_list(reverse) #print(list(data_iterator(reverse))) print("Original Unchanged") print_linked_list(demo_list)

I had to put in a Node class for the code to run.

Similar to above solution

from LinkedList import *

def reverse_linked_list(linked_list):
  if linked_list == None:
    return None
  node = Node(linked_list.data, None)
  while linked_list.next:
      linked_list = linked_list.next
      node = Node(linked_list.data, node)
  return node