I am learning about LinkedList and tried reversing the same using Singly LinkedList collection. The challenge is list.Next is read only. So you can’t change pointers, you have to swap the value.
Also, I am to trying to attain this in the same Singly LinkedList (without creating any new LinkedList) This is my code using another LinkedList, not from Collections, but by creating Node class. Please help!
using System;
using System.Collections.Generic;
using System.Text;
namespace MyProject
{
public class Node
{
public int value;
public Node next;
public Node(int value)
{
this.value = value;
next = null;
}
}
class ReverseSinglyLinkedList : Node
{
ReverseSinglyLinkedList(LinkedList<int> list) : base(list.First.Value)
{
}
public Node reverseList(LinkedList<int> list)
{
LinkedListNode<int> currentNode;
Node new_node = new Node(list.First.Value);
currentNode = list.First.Next;
while (currentNode != null)
{
Node new_currentNode = new Node(currentNode.Value);
new_currentNode.next = new_node;
new_node = new_currentNode;
currentNode = currentNode.Next;
}
return new_node;
}
public static void Main(String[] args)
{
LinkedList<int> list = new LinkedList<int>();
list.AddLast(1);
list.AddLast(2);
list.AddLast(3);
list.AddLast(4);
list.AddLast(5);
ReverseSinglyLinkedList obj = new ReverseSinglyLinkedList(list);
Node revList = obj.reverseList(list);
while (revList != null)
{
Console.WriteLine(revList.value);
revList = revList.next;
}
}
}
}