如何在 Java 中重新排列 LinkedList 而不更改数据字段,仅通过重新排列链接?



首先,我刚刚开始学习LinkedLists,所以如果我说一些关于它的话,我很抱歉,这是完全错误的。我有一个作业,我必须编写一个方法来切换 LinkedList 的对。如果我有一个列表 [3, 7, 4, 9],它会在方法之后更改为 [7, 3, 9, 4]。我不能更改节点的任何数据字段,也不能构造任何新节点。我试图了解LinkedLists是如何工作的。到目前为止,这就是我所拥有的:

public void switchPairs() {
if (front == null)
return;
ListNode current = head;
ListNode next = head.next;
current.next = null;
next.next = current;
}

现在我仍在尝试弄清楚如何交换前两个值。我的理由是,我可以将一个名为current的新ListNode变量分配给head,然后在head.next旁边分配另一个新的ListNode变量。然后我可以将电流之后的节点分配为空。然后,该列表与我创建的下一个变量分开,我可以将下一个节点分配给当前节点。但这行不通。那么我该怎么做呢?

请参考下面的代码:

public void switchPairs() {
if (front == null)
return;
ListNode current = head;
ListNode nextNode = head.next;
current.next = nextNode.next;
head = nextNode; 
head.next = current;

}

希望这个算法能有所帮助...

  1. 将头节点分配到一个临时节点中
  2. 将头部的下一个节点分配到另一个临时节点中
  3. 将步骤 1 的下一个节点
  4. 替换为步骤 2 的下一个节点
  5. 将头下一个节点与在步骤 1 中创建的节点一起分配
  6. 将头节点与在步骤 2 中创建的节点一起分配

您需要遵循以下内容。

1. While temp is not null && temp1 is not null
1. Swap links of temp and temp1
2. Move temp to temp1.next
3. Move temp1 to temp.next if temp is not null 
else make temp is null

交换两个节点链接如下。[开关对(温度,温度1(]

1. newTemp = temp
2. temp.link = temp1.link
3. temp1.link = newTemp

比方说

data|link是我在这里使用的模式。

temp = 3|linkX 
temp1 = 5|linkY
newTemp = temp = Points to the address of Temp
temp.link = 3|linkY [temp.link = temp1.link]
temp1.link = 5|AdrOfTemp [temp1.link = newTemp]

如果您仍有疑问,请发布调用此函数的帮助程序方法。我怀疑您可能错过了切换临时节点。

最新更新