java - 了解家庭作业

标签 java data-structures linked-list

问题是:编写代码以值 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/

相关文章:

java - 为每个元素添加一个按钮到 ListView

java - 修改现有日期,结果将与java格式相同

java - Tomcat JNDI 资源不可访问

javascript - 我应该如何表示数据以有效搜索和比较字符串

c - 编译简单链表程序时出现未声明节点错误

c - 在 C 中删除整个链表 - 为什么不使用引用指针?

c - 将文件内容导入C中的结构

java - 是否可以阻止 JVM 访问特定的 URL?

java - 链表的头节点未更新

c - 将列表和内部字典定义为c中字典的值