[英]Java Generic Doubly Linked List Swap
http://users.cis.fiu.edu/~weiss/dsaajava3/code/MyLinkedList.java
上面的鏈接顯示了我想要修改的代碼,以便具有雙向鏈接列表中的swap方法。 我預先使用URL表示歉意,因為此處粘貼的300行代碼不太可讀。
對於輸出,我只想有一個列表輸出,例如 :
[ 28 27 **21** 25 24 23 22 **26** 20 0 1 2 3 4 5 6 7 8 ] //(2, 7) swap
以下是我的嘗試(部分代碼包含/修改為原始代碼) :
交換方法:
public AnyType swap( int idx, int idx2)
{
return swap( getNode( idx ), getNode ( idx2 ) );
}
private AnyType swap( Node<AnyType> p, Node<AnyType> p2)
{
Node<AnyType> temp = p; //realize it doesn't work due to linking
p = p2;
p2 = temp;
return p.data;
}
主要:
class TestLinkedList
{
public static void main( String [ ] args )
{
MyLinkedList<Integer> lst = new MyLinkedList<>( );
for( int i = 0; i < 10; i++ )
lst.add( i );
for( int i = 20; i < 30; i++ )
lst.add( 0, i );
lst.remove( 0 );
lst.remove( lst.size( ) - 1 );
lst.swap(2, 7);
System.out.println("swap: " + lst);
}
}
輸出
swap: [ 28 27 26 25 24 23 22 21 20 0 1 2 3 4 5 6 7 8 ]
21
我意識到解決問題的方法不是使用鏈表。 我一直在分析要修改的代碼; 但是,在使用指針和雙向鏈表時很難理解編碼部分(不是概念)。 請解釋我應該如何解決。 謝謝。
編輯
/* Swaps idx and idx2 nodes
* @param idx the index of the object
* @param idx2 the index of the object
*/
public void swap( int idx, int idx2)
{
swap( getNode( idx ), getNode ( idx2 ) );
if( idx < 0 || idx >= size( ) || idx2 < 0 || idx2 >= size( )){
throw new IndexOutOfBoundsException( "swap first index: " + idx + ", second index: " + idx2 );
}
}
/**
* Swaps node and data at p and p2
* @param p the index of the object
* @param p2 the index of the object
*/
public void swap( Node<AnyType> p, Node<AnyType> p2)
{
Node<AnyType> temp = p;
p = p2;
p2 = temp;
temp = p.next.prev;
p.next.prev = p2.next.prev;
p2.next.prev = temp;
AnyType dataTemp = p.data;
p.data = p2. data;
p2.data = dataTemp;
}
輸出
[ 29 28 27 26 25 24 23 22 21 20 0 1 2 3 4 5 6 7 8 9 ]
swap: [ 29 28 22 26 25 24 23 27 21 20 0 1 2 3 4 5 6 7 8 9 ]
現在正在工作。 我做對了嗎? 但是我得到編譯錯誤。 我假設它與public void swap( Node<AnyType> p, Node<AnyType> p2)
方法有關,該方法具有warning: exporting non-public type through public API
。 在這里我該怎么辦?
假設您的輸入是:
[ 1 2 3 4 5 6 7 8 9 ]
而您想交換3和7:
[ 1 2 >7< 4 5 6 >3< 8 9 ]
這意味着您需要更新所有這些值:
2.next = 7
7.prev = 2
7.next = 4
4.prev = 7
6.next = 3
3.prev = 6
3.next = 8
8.prev = 3
總共有8個分配,不包括對臨時變量的分配。
如果您想交換5和6怎么辦:
[ 1 2 3 4 >6< >5< 7 8 9 ]
4.next = 6
6.prev = 4
6.next = 5
5.prev = 6
5.next = 7
7.prev = 5
嗯...那只是6個作業。
如果要交換第一個和最后一個元素怎么辦:
[ >9< 2 3 4 5 6 7 8 >1< ]
您沒有共享這部分,但是我假設您同時具有頭和尾引用,所以:
head = 9
9.prev = null
9.next = 2
2.prev = 9
8.next = 1
1.prev = 8
1.next = null
tail = 1
哇,那不一樣。
現在,您只需要編寫所有代碼,小心處理所有組合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.