Okay, so I'm trying to swap two elements in a doubly linked list without altering the data and without using collections. Here's what I have so far;
package q2b;
public class DoublyLinkedList {
static Node first;
static Node last;
public DoublyLinkedList() {
first = null;
last = null;
}
public void display() {
Node current = first;
if(first == null) {
System.out.println("List is empty.");
}
System.out.print("Nodes: ");
while(current != null) {
System.out.print(current.data+", ");
current = current.next;
}
System.out.println();
}
public void add(int x) {
if (last==null) {
Node temp = new Node(x);
last = temp;
first = temp;
}
else {
Node temp = new Node(x);
last.next = temp;
temp.prev = last;
last = temp;
}
}
public Pair find(int x, int y) {
Node n1 = null;
Node n2 = null;
Node temp = first;
while (temp != null) {
if (temp.data == x) {
n1 = temp;
}
else if (temp.data == y) {
n2 = temp;
}
temp = temp.next;
}
return new Pair(n1,n2);
}
public void swap(int x, int y) {
if (first == null || first.next == null || x == y) {
return;
}
Pair p = find(x,y);
Node n1 = p.first;
Node n2 = p.second;
if (n1==first) {
first = n2;
}
else if (n2 == first) {
first = n1;
}
if (n1 == last) {
last = n2;
}
else if (n2 == last) {
last = n1;
}
Node temp;
temp = n1.next;
n1.next = n2.next;
n2.next = temp;
if (n1.next != null) {
n1.next.prev = n1;
}
if (n2.next != null) {
n2.prev.next = n2;
}
temp = n1.prev;
n1.prev = n2.prev;
n2.prev = temp;
if (n1.prev != null) {
n1.prev.next = n1;
}
if (n2.prev != null) {
n2.prev.next = n2;
}
}
}
And my main;
public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.add(2);
list.add(4);
list.add(6);
list.add(8);
list.add(10);
list.display();
list.swap(6, 8);
list.display();
}
}
Now when I go to run the code, it just infinitely runs until it crashes. I assume I'm missing something in the swap function that is sending it into a death spiral, but I'm not sure what it is. Can anyone give me some insight?