Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 交换单链表的最后两个节点_Java_Linked List - Fatal编程技术网

Java 交换单链表的最后两个节点

Java 交换单链表的最后两个节点,java,linked-list,Java,Linked List,如何交换链表的最后两个节点?我正在尝试使用一个助手节点,因为我认为需要它来避免在过程中“丢失”一个节点 ... Node node3 = new Node("Hi", null) ; Node node4 = new Node("Hello", null) ; ... // swap node3 & node4 Node temp = node3.succ ; node3.succ = null ; // this should be the last node now, so i s

如何交换链表的最后两个节点?我正在尝试使用一个助手节点,因为我认为需要它来避免在过程中“丢失”一个节点

...
Node node3 = new Node("Hi", null) ;
Node node4 = new Node("Hello", null) ;
...

// swap node3 & node4
Node temp = node3.succ ;
node3.succ = null ; // this should be the last node now, so i set its pointer to null
node2.succ = temp ; // the second's node successor becomes what used to be the last node
temp = node4 ; // not sure how to use temp here. what should it point to if at anything?

我想我做错了,有什么提示吗?

这看起来像一个单链表。您需要使
node4
成为
node2
的后续节点(其后续节点是
node3
)。您还需要使
node3
成为
node4
的继承者。因此:

  • 获取对
    node2
    node3
    node4
  • node2.succ
    设置为
    node4
  • node4.succ
    设置为
    node3
  • node3.succ
    设置为
    null

  • 如果不显式地获取对所有3个节点的引用,则可以更简单/有效地执行此操作(尽管不太清楚),但这应该可以让您开始了。

    假设您有一个链表
    a->B->C
    ,并且您想交换
    B
    C

  • 设置T*=B(将B存储在某处)
  • 设置A.next=C
  • 设置T*.next=C.next(这是对列表末尾的操作的概括)
  • 设置C.next=T*

  • 实际上,您必须跟踪三个节点—最后两个要切换的节点,以及它们之前的一个节点,以便更新其指针


    或者,您可以交换节点值。

    好吧,您已经得到了正确的答案:-)

    temp和node4引用同一个对象。所以你已经成功地交换了它们。现在,您可以让temp不在范围内(即,不要管它)

    所以您不需要将temp设置为任何值