使用参数(节点<e>节点)

时间:2015-10-10 20:52:07

标签: java singly-linked-list

我面临的问题是弄清楚如何编写方法

public SingleLinkedList copy(Node <E> node) {

}

返回列表的副本。我试过了:

public SingleLinkedList copy(Node <E> node) {
 SingleLinkedList<E> temp = new SingleLinkedList<E>();
 Node<E> ref = head;
  for(Node<E> n = ref ;ref!= null; n = n.next){
    temp.add(n, ref.data);
  ref = ref.next;
 }
  return temp;
}

我创建了一个名为temp的新列表,将head更改为ref,遍历列表并将其添加到新列表并返回新列表,但temp.add(n, ref.data)出现错误。

我可能做错了什么?

class SingleLinkedList<E> {

private static class Node<E> {
    private E data;//removed final * private final E data
    private Node<E> next;

    private Node(E item) {
        data = item;
    }
}

private Node<E> head;
private int size;

/* Insert item at index, returns true if add is successful. */
public boolean add(int index, E item) {
    if (index < 0 || index > size) {
        throw new IndexOutOfBoundsException("" + index);
    }

    if (index == 0) { // adding to the front
        Node<E> t = head;
        head = new Node<>(item);
        head.next = t;
    } else { // adding anywhere other than front
        Node<E> left = getNode(index - 1);
        Node<E> node = new Node(item);
        Node<E> right = left.next;
        left.next = node;
        node.next = right;
    }
    size++;
    return true;
}

/* Add item at end of list, returns true if successful. */
public boolean add(E item) {
    return add(size, item);
}

/* Return item at index */
public E get(int index) {
    if (index < 0 || index >= size) {
        throw new IndexOutOfBoundsException("" + index);
    }
    return getNode(index).data;
}

/* Return the number of items */
public int size() {
    return size;
}

/* Returns a string representation of the list */
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (Node<E> n = head; n != null; n = n.next) {
        sb.append(n.data);
        sb.append(" ");
    }
    sb.append("]");
    return sb.toString();
}

/* Return the node at location index */
private Node<E> getNode(int index) {
    Node<E> n = head;
    for (int i = 0; i < index; i++)
        n = n.next;
    return n;
}

1 个答案:

答案 0 :(得分:0)

问题是您需要将该位置作为int传递。我也删除了Node n因为你不需要它。 我认为这应该有用。

public SingleLinkedList copy() {
    SingleLinkedList<E> temp = new SingleLinkedList<E>();
    int i = 0;
    for(Node<E> ref = head ;ref!= null; ref = ref.next){
        temp.add(i++, ref.data);
    }
    return temp;
}
编辑:我忘记删除你根本不需要它的参数。