I wanted to flip a Double Linked List and put it into a new List. But I don't know how to solve the Problem. My Code looks like this and I think it makes sense, but it doesn't work at all.
getPred = previous getSucc = next
public DoublyLinkedList fliping()
{
DoublyLinkedList newList = new DoublyLinkedList();
Element current = last;
Element toInsert = newList.first;
while(current != null)
{
current.disconnectPred();
Element temp = current.getPred();
Element temp2 = current.getPred().getPred();
if(toInsert == newList.first)
{
temp.connectAsSucc(temp2);
temp2.connectAsPred(temp);
toInsert.connectAsSucc(temp);
newList.size ;
}
if(temp2 == null)
{
temp.connectAsSucc(temp2);
toInsert.connectAsSucc(temp);
newList.size ;
}
temp.connectAsSucc(temp2);
temp2.connectAsPred(temp);
toInsert.connectAsSucc(temp);
toInsert.connectAsPred(temp2);
toInsert = toInsert.getSucc();
current = current.getPred();
newList.size ;
size--;
}
return newList;
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Element.getPred()" because the return value of "Element.getPred()" is null
at DoublyLinkedList.fliping(DoublyLinkedList.java:282)
at Testumgebung.testDoublyLinkedList(Testumgebung.java:35)
at Testumgebung.main(Testumgebung.java:7)
I tried to disconnect the last element and the second last element. Than i tried to connect them to each other and put them togeter, as the first and second element into the new List
CodePudding user response:
If your DoublyLinkedList
implements the interface java.util.List
I would first ensure that you can copy it (e.g. with a copy-constructor that initializes it with any other Collection
or List
- don't implement the clone
method, too much hassle with that!).
Then simply use the method java.util.Collections.reverse(List<?>)
on a 1:1 copy of your original list.