I've made a link list program in C# but I also want to reverse the numbers in the link list. The program runs and lets me add the numbers to the list but once I've added the numbers, the numbers don't appear for the reverse part, it just outputs "Reverse list". How can I display the numbers in reverse order?
using System;
namespace LinkedList
{
class Program
{
public class Node
{
public int data;
public Node next;
};
static Node add(Node head, int data)
{
Node temp = new Node();
Node current;
temp.data = data;
temp.next = null;
if (head == null)
head = temp;
else
{
current = head;
while (current.next != null)
current = current.next;
current.next = temp;
}
return head;
}
static void reverse_list(Node head)
{
Node prev = null, current = head, next = null;
while (current != null)
next = current.next;
current.next = prev;
prev = current;
current = next;
}
static void print_numbers(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
static Node List(int[] a, int n)
{
Node head = null;
for (int i = 1; i <= n; i++)
head = add(head, a[i]);
return head;
}
public static void Main(String[] args)
{
int n = 10;
int[] a;
a = new int[n + 1];
a[0] = 0;
Console.WriteLine("Add values to the list");
for (int i = 1; i <= n; i++)
a[i] = int.Parse(Console.ReadLine());
Node head = List(a, n);
Console.WriteLine("Linked List: ");
print_numbers(head);
Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Reversed list: ");
reverse_list(head);
print_numbers(head);
}
}
}
If you want to do this with your singly linked list you're going to have to crawl the list and re-link everything
For a list A>B>C>D>E
you'll need a current of B, prev of A and next of C. You'll need to change current to point at prev then advance everything along by one until you reach the end
/*
A>B>C>D>E
A<B C>D>E
A<B<C D>E
A<B<C<D<E
*/
var prev = head; //A
var curr = head.Next; //B
var next = curr.Next; //C, we need this so C is not lost when we re-point B at A in loop line 1
prev.Next = null; //null<A B>C>D>E
while(true)
{
curr.Next = prev; //null<A<B C>D>E
prev = curr; //prev is now B, was A
curr = next; //curr is now C, was B
if(curr.Next != null){
next = curr.Next; //next is now D, was C
} else {
head = curr;
break;
}
}
I think that's the logic; havent tested it