【问题标题】:Double Chained List in JavaJava中的双链表
【发布时间】:2021-04-29 05:17:56
【问题描述】:

我必须实现类“DoubleChainedList”和“Elem”。DoubleChainedList 管理一个双链列表,而 Elem 是关联的节点类,具有指向后继者和前驱者的指针。

我必须实现以下方法:

public void removeAtIndex(int i) // 移除位置 i 处的元素。如果 i > length-1 或 i

  • public int[] toArray() // 将列表作为数组返回

双链表

import java.util.Collections;
import java.util.LinkedList;

public class DoubleChainedList {

    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(4);
        list.add(1);
        list.add(7);
        list.add(2);
        list.add(9);
        Integer[] arr = list.toArray(new Integer[0]);

        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

public int[] toArray() {

        Integer[] arr = list.toArray(new Integer[0]);
        return null;

    }

    public int smallest() {
        int min = Integer.MAX_VALUE;

        // Check loop while head not equal to NULL
        while (head != null) {
            if (min > head.data)
                min = head.data;

            head = head.next;
        }
        return min;
    }

埃莱姆:

public class Elem {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    private Node head = null;
    private Node tail = null;

    public class Node {
        public int data;
        public Node next;
        public Node prev;

    }

}

我的问题:它向我显示以下错误:无法解决头部问题 一个变量,我的问题是如何修复它?

【问题讨论】:

  • headElem 类的成员,而不是 DoubleChainedList 类的成员。
  • @Benoit 感谢您的建议。那么我应该在 DoubleChainedList 类中添加 head 吗?
  • 您可以在 google 上搜索 java“双链表”并找到许多示例。

标签: java linked-list


【解决方案1】:

您的DoubleChainedList 应该有一个head 和一个tail。这些分别是列表的开头和结尾。列表中的每个节点(您被指示命名为Elem)都应该有一个prev 和一个next 类型为Elem。您的 Elem 类包含另一个名为 Node 的类 - 这似乎是多余的,可能会让您感到困惑 - 将其扁平化为 Elem 类。

您的smallest() 方法包含错误,因为它正在更改列表。创建一个单独的 Elem 变量来导航列表的内容 - 不要在此处更改 headtail

当列表为空时返回 Integer.MIN_VALUE 会产生误导。如果列表为空,请考虑抛出异常。您会发现,您必须在列表实现的几乎所有方法中为 is-empty 情况定义特殊处理。

public class DoubleChainedList {
  private Elem head;
  private Elem tail;

  // using protected here because you aren't exposing this to consumers
  // but its available for extension
  protected class Elem {
    private int data;
    private Elem prev;
    private Elem next;
  }

  public int smallest() {
    if (head == null) {
      throw new Exception("list is empty - no smallest value");
    }
    int min = Integer.MAX_VALUE;

    Elem cursor = head;
    while (cursor != null) {
      min = Math.min(min, cursor.data);
      cursor = cursor.next;
    }
    return min;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2015-08-05
    • 1970-01-01
    • 2018-09-16
    相关资源
    最近更新 更多