简体   繁体   English

双链表中的逻辑问题

[英]Logic problems in Doubly Linked List

I seem to have some logic problems happening with my code, I'm new to programming and especially to linked lists. 我的代码似乎发生了一些逻辑问题,我是编程的新手,尤其是链表。 How do my methods in DLL look? DLL中的方法看起来如何? Ihey don't seem to work when called from my application class (add after only works for the first word). 从应用程序类中调用时,它似乎不起作用(添加后仅对第一个单词起作用)。

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());

The problem is here: 问题在这里:

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> (????) } }

At first, as you have noticed, you need a node instead of an E . 首先,您已经注意到,您需要一个节点而不是E Besides, you find the Node which contains the prev element. 此外,找到包含prev元素的Node。 So you should add Node<E> prevNode = search(prev); 因此,您应该添加Node<E> prevNode = search(prev); before the if statement, and replace the prev with prevNode . 在if语句之前,将prev替换为prevNode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM