简体   繁体   中英

Reversing single linked list

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?

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--

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;
    }
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM