问题是:编写代码以值 x 为中心对链表进行分区,使得所有小于 x 的节点都位于所有大于或等于 x 的节点之前。
我得到了这个答案:
public Node partition(Node head, int x) {
Node firstHead = null;
Node secondHead = null;
Node n = head;
if (head == null) {
return null;
}
while (n != null) {
Node next = n.next;
if (n.data < x) {
n.next = firstHead; *
firstHead = n;
}
else {
n.next = secondHead;
secondHead = n;
}
n = next; **
}
if (firstHead == null) {
return secondHead;
}
else {
n = firstHead;
while (n.next != null) {
n = n.next;
}
n.next = secondHead;
return firstHead;
}
}
例如,如果列表是 3 7 9 1 4 8 2 3 并且您要在 x=4 处进行分区,那么在第一个 while 循环内,第二个元素 (7) 将设置为 null(其中有一个星号)代码)然后 n 将再次设置为 7(其中有两颗星)。我不太确定这是如何工作的?是否创建了 LinkedList 中的另一个节点并将 null 推回?抱歉给您带来麻烦
最佳答案
您似乎对几行内容有疑问,所以我会尝试解释一下
n.next = firstHead; // This is the first step of an Insert, remove the next pointer.
// There may be (and is) a second level of looping where we
// find the new next value, but it might involve a second swap.
firstHead = n; // so make sure to store the current node.
n = next; // continue down the list of nodes to find the correct place for
// firstHead (if we have one).
如果我的问题有误,我会删除此答案。
关于java - 了解家庭作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591569/