I'm trying to reverse a linked list and I wrote the code for that. But, when I print the list after reversing it, the output is kinda incomplete.
public void reverseDoubly() {
Node temp = null;
Node current = head;
if(current == null) System.out.println("Cannot reverse an empty list!");
while(current!=null) {
temp = current.previous;
current.previous = current.next;
current.next = temp;
current = current.previous;
}
if(temp!=null) {
head = temp.previous;
}
}
public class Main {
public static void main(String[] args) {
Doubly d1 = new Doubly();
d1.insertFirst(80);
d1.insertLast(90);
d1.insertLast(100);
d1.insertLast(120);
d1.insertAtPos(3, 110);
d1.reverseDoubly();
d1.print();
}}
Output: 120 110 100
In my view
temp
should behead
andcurrent
should behead.next
.So the code would look like this:
The complete code via C# (do not worry it is can be easily converted to C#) would look like this:
and
LinkedList<T>
:public class LinkedList { public Node Head { get; set; }