Skip to content

206 Reverse Linked List

Leetcode

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

alt

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2: alt

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

C# Solution

using System;
using System.Collections.Generic;

namespace Algorithms.Simple
{
  public class ReverseLinkedList
  {
    public static ListNode Reverse(ListNode root)
    {
      ListNode prev = null;
      ListNode current = root;

      while (current != null)
      {
        var tempNext = current.next;
        current.next = prev;
        prev = current;
        current = tempNext;
      }

      return prev;
    }
  }
}

C# Tests

using System;
using Algorithms.Simple;
using Xunit;

namespace AlgorithmTests.Simple
{
  public class ReverseLinkedListTests
  {
    [Fact]
    public void ValidTest1()
    {
      var nodeList = new ListNode[5];
      var node1 = new ListNode(2);
      var node2 = new ListNode(3);
      var node3 = new ListNode(4);
      var node4 = new ListNode(5);
      var node5 = new ListNode(5);

      node1.next = node2;
      node2.next = node3;
      node3.next = node4;
      node4.next = node5;

      Assert.Equal(ReverseLinkedList.Reverse(node1), node5);
    }

    [Fact]
    public void ValidTest2()
    {
      var nodeList = new ListNode[2];
      var node1 = new ListNode(1);
      var node2 = new ListNode(2);

      node1.next = node2;

      Assert.Equal(ReverseLinkedList.Reverse(node1), node2);
    }
  }
}