【问题标题】:Reviewing an append function for a linked list查看链表的附加函数
【发布时间】:2018-07-30 21:21:00
【问题描述】:

这是一个练习题,我确信是正确的,但是在查看了网站上的类似示例后,我觉得有必要仔细检查。

考虑在整数链表中的节点声明:

class LinkedListNode {
     int x;
     LinkedListNode next;
}

制作一个满足以下要求的递归方法追加:如果 H 是整数链表的头部且 t 是整数,则 add(H, T) 是整数链表来自于将 T 添加到以 H 为头部的列表的末尾。

private Node append(Node H, int t){
    if (H == null) {
        H = new Node(x);
    }
    else {
        H.next = append(H.next, t);
    }
    return H;
}

我在这里查看了其他问题,但我仍然有些怀疑我是否正确。任何帮助将不胜感激。

【问题讨论】:

  • 你为什么不运行你的代码,看看它是否有效?此外,我建议更改您的编码约定,为变量使用 lowerCamelCase 表示法,并为类名保留大写字母。原因是乍一看,大多数人会将 H 视为类名而不是变量。将其从 H 更改为 h 会稍微清除一下。
  • 我认为H = new Node(x); 应该是H = new Node(t);
  • Node 应该是LinkdListNode。而LinkedListNode 将需要声明构造函数LinkedListNode(int x)

标签: java linked-list append


【解决方案1】:

我将为 LinkedList 类创建一个名为 append 的公共方法,如下所示:

public Node append(int t) {
    processAppend(firstNode, t);
}

还有一个私有方法processAppend,看起来像这样:

private Node processAppend(Node n, int t) {
    if (n == null) {
        Node nn = new Node(t);
        n.setNext(n);
    }
    else {
        return append(n.getNext(), t);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多