我的LinkedList的size()有什么问题吗?

时间:2017-02-06 19:04:06

标签: java algorithm data-structures collections linked-list

我需要帮助我的自定义链表,我无法弄清楚问题。需要一些帮助。 这是我的size()方法:

  public ObjectLinkedList() {
    firstNode = null;
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: add() description: Insert an item into the list
 *
 * @param index position of the list
 * @param obj the element is going to be inserted
 * @author Jinyu Wu Date: 2017/2/4
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public void add(int index, Object obj) {
    Node tempNode = firstNode;
    Node currentNode = new Node(obj);
    if (index == 0) {
        firstNode = currentNode;
        return;
    }
    if (index < 0 || index > size()) {
        System.out.println("add(ObjectLinkedList) index out of bound exception");
    } else {
        for (int i = 1; i <= index; i++) {
            tempNode = tempNode.getNext();
            if (i == index - 1) {
                if (index != size() - 1) {
                    currentNode.setNext(tempNode.getNext());
                } else {
                    currentNode.setNext(null);
                }
                tempNode.setNext(currentNode);
            }
        }
    }

}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: removeAt() description: remove an item from a position of the
 * list
 *
 * @param index position in the list
 * @author Jinyu Wu Date: 2017/2/4
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public void removeAt(int index) {
    if (index < 0 || index > size()) {
        System.out.println("removeAt(ObjectLinkedList) index out of bound exception");
    } else {
        Node tempNode = firstNode;
        if (index == 0) {
            firstNode = firstNode.getNext();
        } else {
            for (int i = 1; i <= index; i++) {
                if (i == index - 1) {
                    if (index != size() - 1) {
                        tempNode.setNext(tempNode.getNext().getNext());
                    } else {
                        tempNode.setNext(null);
                    }
                }
                tempNode = tempNode.getNext();
            }
        }
    }

}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: remove() description: remove a specific item from a position of
 * the list
 *
 * @param obj target object is going to be removed
 * @author Jinyu Wu Date: 2017/2/4
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public void remove(Object obj) {
    if (size() > 0) {
        Node tempNode = firstNode;
        for (int i = 0; i <= size(); i++) {
            if (tempNode.equals(obj)) {
                tempNode.setNext(tempNode.getNext().getNext());
                break;
            }
            if (i < size() - 1) {
                tempNode = tempNode.getNext();
            }
        }

        System.out.println("target object is not found inside the linkedList(remove)");
    }
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: get() description:get an item from the list
 *
 * @param index position in the list
 * @author Jinyu Wu Date: 2017/2/4
 * @return double ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public Object get(int index) {
    if (index < 0 || index > size()) {
        System.out.println("get(ObjectLinkedList) index out of bound exception");
        return null;
    } else if (index == 0) {
        return firstNode.getValue();
    } else {
        Node tempNode = firstNode;
        for (int i = 0; i <= index; i++) {

            if (i == index - 1) {

                return tempNode.getValue();
            }
            tempNode = tempNode.getNext();
        }
        System.out.println("objectLinkedList get method nothing found");
        return null;
    }

}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: toString() description: print out the content of the list
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @return Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public String toString() {
    Node tmp = firstNode;
    String res = "" + firstNode;
    while (tmp.getNext() != null) {
        tmp = tmp.getNext();
        res += "," + tmp;
    }
    return "ObjectLinkedList{" + res + "}";
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: find() description:get an item from the list
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @param obj Object is going to be found
 * @return Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public int find(Object obj) {
    Node tempNode = firstNode;

    if (obj.equals(firstNode.getValue())) {
        return 0;
    } else {
        for (int i = 1; i < size(); i++) {
            tempNode = tempNode.getNext();
            if (tempNode.getValue().equals(obj)) {
                return i;
            }

        }
        return -1;
    }

}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: size() description:get the size of the list
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @return Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
@Override
public int size() {
    int size = 1;
    if (firstNode == null) {
        return 0;
    }
    try {
        for (Node n = firstNode; n.getNext() != null; n = n.getNext()) {
            size++;
        }
        return size;
    } catch (NullPointerException e) {
        return size;
    }
}

这是我的Node类:

public class Node {

private Node nextNode;
private Object obj;

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: Node() description: constructor
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @param obj set the value
 */
public Node(Object obj) {
    this.obj = obj;
    this.nextNode = null;
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: getValue() description: get the value of object
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @return return the object
 */
public Object getValue() {
    return this.obj;
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: setValue() description: setValue for the Node
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @param obj return the value
 */
public void setValue(Object obj) {
    this.obj = obj;
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: getValue() description: get the next value of the currentNode
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @return return next node
 */
public Node getNext() {
    if (nextNode != null) {
        return this.nextNode;
    } else {
        return null;
    }
}

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Method: setNext() description: set next value for the Node
 *
 * @author Jinyu Wu Date: 2017/2/4
 * @param node set next node
 */
public void setNext(Node node) {
    this.nextNode = node;
}

}

我的大小编号一直不正确,但我无法弄清楚问题。

这是我在main方法中的代码:

 list = new ObjectLinkedList();
    m1 = new Money(5, (byte) 6);
    node1 = new Node(m1);
    list.add(0, node1);
    m2 = new Money(2, (byte) 4);
    node2 = new Node(m2);
    list.add(1, node2);
   System.out.println(list.Size());

我一直得到1而不是2;

3 个答案:

答案 0 :(得分:0)

size

中添加ObjectLinkedList字段
private int size;

在添加新项目之前在行中增加它,并在从列表中删除项目之前将其减少到行中。

然后只需添加一个方法:

public int getSize() {
  return this.size;
}

由于OP要求发布递归方法(这是低效的!):

public int size(ObjectLinkedList list) {
    if (list.firstNode == null)
        return 0;
    return 1 + size(list.firstNode.getNext());
}

答案 1 :(得分:0)

找到错误

错误存在于add(int, Object)方法中,更确切地说,位于以下构造中:

for (int i = 1; i <= index; i++) {
    tempNode = tempNode.getNext();
    if (i == index - 1) {
        if (index != size() - 1) {
            currentNode.setNext(tempNode.getNext());
        } else {
            currentNode.setNext(null);
        }
        tempNode.setNext(currentNode);
    }
}

第二次向列表中添加资金时,请致电list.add(1, node2)。但是,从index = 1开始i1递增,i == index - 1永远不会是true

因此,第二个对象根本没有插入到您的列表中。您可以通过调用toString()方法进行检查。

寻找解决方案

我猜你这样做if - 子句,因为你希望嵌套在里面的代码仅在tempNode是你正在寻找的时才执行。但是,通过将代码放在for - 循环后面并使用其条件,您可以更轻松地完成此操作:

for(int i = 1; i < index; i++) {
    tempNode = tempNode.getNext();
}
if(index != size() - 1) {
    currentNode.setNext(tempNode.getNext());
}
// we just created this node, so we can be quite sure that it does not have a next node set
// else {
//     currentNode.setNext(null);
// }
tempNode.setNext(currentNode);

附注

您的列表已经包含了Node中的对象,因此您无需在main方法中执行此操作。因此,而不是

list = new ObjectLinkedList();
m1 = new Money(5, (byte) 6);
node1 = new Node(m1);
list.add(0, node1);
m2 = new Money(2, (byte) 4);
node2 = new Node(m2);
list.add(1, node2);
System.out.println(list.size());

你应该能够写

list = new ObjectLinkeList();
m1 = new Money(5, (byte) 6);
list.add(m1);
m2 = new Money(2, (byte) 4);
list.add(m2);
System.out.println(list.size());

或只是

list = new ObjectLinkeList();
list.add(new Money(5, (byte) 6));
list.add(new Money(2, (byte) 4));
System.out.println(list.size());

答案 2 :(得分:0)

获取链表的大小就是遍历它。下面我提供了三个遍历链表的选项:for循环,while循环和递归。

class ObjectLinkedList<T> {

  public static void main(String... args) {
    final ObjectLinkedList<String> list = new ObjectLinkedList<>();
    list.add(0, "World");
    list.add(0, "Hello");
    list.add(2, "!");
    System.out.println(list);
    System.out.println(list.size());
  }

  private Node<T> firstNode = null;

  public void add(int index, T obj) {
    final Node<T> newNode = new Node<>(obj);
    Node<T> tempNode = firstNode;
    if (index == 0) {
      firstNode = newNode;
      firstNode.setNext(tempNode);
      return;
    } else {
      int count = 0;
      //option 1: a for loop
      for (Node<T> current = firstNode; current != null; current = current.getNext()) {
        tempNode = current.getNext();
        if (++count == index) {
          current.setNext(newNode);
          newNode.setNext(tempNode);
          return;
        }
      }
    }
    throw new IndexOutOfBoundsException("Out of bounds!");
  }

  public String toString() {
    Node<T> tmp = firstNode;
    StringBuilder res = new StringBuilder("ObjectLinkedList: [");
    //option 2: a while loop
    while (tmp != null) {
      res.append(tmp);
      tmp = tmp.getNext();
      if (tmp != null) {
        res.append(", ");
      }
    }
    return res.append("]").toString();
  }

  public int size() {
    return distanceFromEnd(firstNode);
  }

  //option 3: recursion
  private int distanceFromEnd(Node<T> startingNode) {
    if (startingNode == null) {
      return 0;
    } else {
      return 1 + distanceFromEnd(startingNode.getNext());
    }
  }
}

class Node<T> {

  private Node<T> next = null;
  final private T value;

  public Node(final T value) {
    assert value != null;
    this.value = value;
  }

  public Node<T> getNext() {
    return next;
  }

  public void setNext(final Node<T> next) {
    this.next = next;
  }

  public T getValue() {
    return value;
  }

  @Override
  public String toString() {
    return value.toString();
  }
}