Reputation: 27385
I tried to revert single linkied list as follows:
public class MutableLst<T> {
public T current;
public MutableLst<T> next;
private MutableLst(T current){
this.current = current;
}
public static <T> MutableLst<T> create(T current){
return new MutableLst<T>(current);
}
public void reverse(){
MutableLst<T> newNext = null;
MutableLst<T> nxt = next;
next = newNext;
while(nxt != null) {
newNext = this; //<------- cycle is here
current = nxt.current;
next = newNext;
nxt = nxt.next;
}
}
But this implementation does not work. When I assign to this
I got a cycle. How to fix it?
Upvotes: 1
Views: 70
Reputation: 150
Your code's problem is that you never assign a value to next. Here's my iterative solution to your problem. Also, to make it easier on yourself I would suggested having a head that references the beginning of your linked list.
public void reverse() {
MutableLst<T> prev = null;
MutableLst<T> curr = head;
MutableLst<T> next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
}
head = prev;
Upvotes: 0
Reputation: 76564
I would use recursion, like this:
public void reverse(MutableLst<T> previous){
if (this.current.next !== null) {
this.next.reverse(this);
}
this.next = previous;
}
public void reverse() {
reverse(null);
}
You will need to call reverse to the head of your list. As about your concrete problem, you are changing the next before you get a chance to use it. You might want to do something like this instead:
public void reverse(){
MutableLst<T> previous = null;
MutableLst<T> currentItem = this;
MutableLst<T> nxt = null;
while(currentItem != null) {
nxt = currentItem.next;
currentItem.next = previous;
previous = currentItem;
currentItem = nxt;
}
}
Upvotes: 0
Reputation: 1907
You are reversing only the list, so I don't know why do you want to do something with "this" object. Anyway I think you should just use this: https://www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/api/list/MutableList.html#reverseThis--
Upvotes: 2