Skip to content

Instantly share code, notes, and snippets.

@dev-chee
Created November 1, 2021 08:47
Show Gist options
  • Save dev-chee/0863eaa44b5280f6a81ba4d84553e701 to your computer and use it in GitHub Desktop.
Save dev-chee/0863eaa44b5280f6a81ba4d84553e701 to your computer and use it in GitHub Desktop.
revert a list
using System;
namespace hello_csharp
{
class Program
{
class Node
{
public int val;
public Node next;
public Node(int val, Node next = null)
{
this.val = val;
this.next = next;
}
}
static void Main(string[] args)
{
// construct a list (1 -> 2 -> 3 -> 4 -> 5 -> NULL)
var head = new Node(1);
var prv = head;
for (var i = 2; i <= 5; i++)
{
var node = new Node(i);
prv.next = node;
prv = node;
}
Print(head);
// reverse the list (1 <- 2 <- 3 <- 4 <- 5 <- NULL)
prv = null;
var cur = head;
while (cur != null)
{
var node = cur.next;
cur.next = prv;
prv = cur;
cur = node;
}
head = prv; // new the head of list
Print(head);
}
// print the list
static void Print(Node head)
{
var cur = head;
while (cur != null)
{
Console.Write($"{cur.val} ");
cur = cur.next;
}
Console.WriteLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment