gpt4 book ai didi

java - 为什么我的reverse()方法会反转两个MyLinkedList对象?

转载 作者:行者123 更新时间:2023-12-01 18:30:37 26 4
gpt4 key购买 nike

我正在创建一个双向链表类,但我被这个反向()方法困住了。我希望使用reverse()方法创建并返回一个新的MyLinkedList,它与旧的MyLinkedList相反,而不改变旧的。

public MyLinkedList<AnyType> reverse()
{
MyLinkedList<AnyType> list = this;

for(int i=0,j=list.theSize-1; i < list.theSize/2; i++, j--)
list.swap(i,j);

return list;
}

public void swap(int index1, int index2)
{
if(index1 == index2)
return;
else if(index1 > theSize-1 || index2 > theSize-1)
{
try{
throw new IndexOutOfBoundsException();
}
catch(IndexOutOfBoundsException e)
{
System.out.println("IndexOutOfBoundsException\n");
return;
}
}
Node<AnyType> first;
Node<AnyType> last;
if(index1 < index2)
{
first = this.getNode(index1);
last = this.getNode(index2);
}
else
{
first = this.getNode(index2);
last = this.getNode(index1);
}
if((index1 == 0 && index2 == theSize -1) ||(index1 == theSize -1 && index2 == 0))
{
first.next.prev = last;
last.prev.next = first;

first.prev = last.prev;
last.next = first.next;

first.next = endMarker;
endMarker.prev = first;
last.prev = beginMarker;
beginMarker.next = last;
}

else if(Math.abs(index1-index2) == 1)
{
first.next = last.next;
last.prev = first.prev;
first.prev = last;
last.next = first;
last.prev.next = last;
first.next.prev = first;
}

else
{
Node<AnyType> tempNext = last.next;
Node<AnyType> tempPrev = last.prev;

last.next.prev = first;
last.prev.next = first;
first.prev.next = last;
first.next.prev = last;

last.next = first.next;
last.prev = first.prev;
first.next = tempNext;
first.prev = tempPrev;
}
}
public static void main( String [ ] args )
{
MyLinkedList<Integer> lst = new MyLinkedList<>( );
MyLinkedList<Integer> lst2 = new MyLinkedList<>( );

for( int i = 0; i < 10; i++ )
lst.add( i );
System.out.println("Original List: " + lst);

lst2 = lst.reverse();
System.out.println("Original List: " + lst);
System.out.println("Reversed List: " + lst2);
}

这是我的输出:

Original List: [ 0 1 2 3 4 5 6 7 8 9 ]
Original List: [ 9 8 7 6 5 4 3 2 1 0 ]
Reversed List: [ 9 8 7 6 5 4 3 2 1 0 ]

正如您所看到的,原始列表也被颠倒了。为什么会发生这种情况?

最佳答案

原因如下:

lst2 = lst.reverse();

您正在调用 reverse()lst所以lst将会被逆转。然后将结果分配给 lst2这也将被保留。解决方案是深度复制 lst ,分配它lst2并调用

lst2.reverse();

而不是这个:MyLinkedList<AnyType> list = this;

试试这个:

for( int i = 0; i < 10; i++ )
list.add( this.getNode(i) );

关于java - 为什么我的reverse()方法会反转两个MyLinkedList对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24376852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com