Reverse a linkedList from a array

Liam :

I am trying to add a reverse linked list back to a linked list from an array.

public void reverse(){
        //Calling function to take a linked list and put it inside an array
        int[] myArray = this.toArray();
    //Populate list using array             
    for (int i= 0; i < myArray.length; i++){

            this.addHead(myArray[i]);

        }

        System.out.println(this.toString());

    }

Here is my method this works fine but it only set the linked list to the last index and stops.

EX.

[1,7,7,6]

lS.reverse()

=> [6]

Here is the to array function

//Return int array of list values
    public int[] toArray(){

        //Creating a array of the size of linkedList
        //New copy of head
        int f[] = new int[this.size()];
        Node newHead = head;  
        int arrayIndex = 0;

        while(newHead != null){

            //Set the current Index to the data at head location
            f[arrayIndex] = newHead.data();

            //Moves the head to next postion 
            newHead = newHead.next(); 

            //Increment index
            arrayIndex = arrayIndex + 1;
        }

        return f;

    }

The result I am looking to acheive is after reverse() is called I will get from

[1,7,7,6]

To A linked list

6,7,7,1

Mär :

Don't know what you are trying to achieve, but if the initial list is given, there is no need for an array conversion. You can implement something along these lines:

public <T> List<T> reverseList( List<T> list )
    {
        List<T> newList = new ArrayList<T>();
        for( int i = 0; i < list.size(); i++ )
        {
            newList.add( list.get( list.size() - ( i + 1 ) ) );
        }

        return newList;
    }

If arrays are absolutely needed for some reason, you can use this analogously. Create an array, fill up by reversing index order.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25332&siteId=1