Reverse a linkedList from a array

北城以北 提交于 2020-03-23 12:04:22

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/60544362/reverse-a-linkedlist-from-a-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!