配列からLinkedListのを逆に

リアム:

私は、アレイからのリンクリストへの逆リンクリストバックを追加しようとしています。

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());

    }

ここに私の方法は、この作品の罰金ですが、それだけで最後のインデックスと停止にリンクリストを設定します。

EX。

[1,7,7,6]

lS.reverse()

=> [6]

ここでは配列関数にあります

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

    }

私はacheiveに探しています、結果は後にあるreverse()私から取得すると呼ばれています

[1,7,7,6]

リンクリストへ

6,7,7,1

マーチ:

あなたが達成しようとしているか知っているが、初期リストが指定された場合、配列を変換する必要はありませんしないでください。あなたはこれらの線に沿って何かを実装することができます。

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

配列は絶対に何らかの理由で必要とされている場合は、同様にこれを使用することができます。配列を作成し、インデックス順を逆にして埋めます。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=25489&siteId=1