双链表中的逻辑问题

时间:2014-04-15 04:43:55

标签: java algorithm list doubly-linked-list

我的代码似乎遇到了一些逻辑问题,我是编程新手,尤其是链表。 我在DLL中的方法看起来如何?从我的应用程序类调用时,Ihey似乎不起作用(仅在第一个单词后才添加)。

public void addAfter(E elem, E prev) {   //use search method then insert
      if (search(prev) == null){
        insert(elem, last);
      }
      else{
        insert(elem, prev); //prev needs to be of type Node<E> rather than just <E> (????)
      }
    }

private void insert(E elem, Node<E> prev) { //HELP
      Node<E> newNode = new Node<E>(elem, prev, null);
         //if list is empty, add to front
      if (first == null) {
         first= newNode;
         last = newNode;
      } else if (prev == null){
         //addFirst(newNode);
         first.prev = newNode;
         newNode.next = first;
         first = newNode;
      }
      //if at end of list
      else if (prev.next == null){
         prev.next = newNode;
         last = newNode;
      }
      else{
         newNode.next = prev.next;
         newNode.next.prev = newNode;
         prev.next = newNode;
      }
   }

    * @param elem  The element to search for.
    * @return The first Node containing the given element, or null if no Node
    *         contains the element.
    */
   private Node<E> search(E elem) { //HELP
      for (Node<E> curr = first; curr != null; curr = curr.next){
         if (curr.element.equals(elem)){
            return curr;
         }
      }
      return null;
   }





public static void handleLine(String values, DLL<String> list){
      Scanner tokens = new Scanner(values);
      if (tokens.hasNext("[aesdpr]")){
         char command = tokens.next().charAt(0);
         System.out.println("test before switch");
         switch (command){
         case 'a':
            while (tokens.hasNext()){
              String nextToke = tokens.next();
               if (tokens.hasNext()){
                  list.addAfter(nextToke, tokens.next());

1 个答案:

答案 0 :(得分:0)

问题在于:

public void addAfter(E elem, E prev) { //use search method then insert if (search(prev) == null){ insert(elem, last); } else{ insert(elem, prev); //prev needs to be of type Node<E> rather than just <E> (????) } }

首先,正如您所注意到的,您需要一个节点而不是E。此外,您还可以找到包含prev元素的Node。因此,您应在if语句前添加Node<E> prevNode = search(prev);,并将prev替换为prevNode