链接列表不起作用

时间:2014-04-02 01:59:28

标签: java linked-list

我无法实现我的链接列表。当我运行代码时,它不会产生任何东西并继续运行。

更新:我编辑了toString看起来像这样:

 LinearNode<T> current = head;
  String result = "";

  while (current != null) {
     result = result + (current.getElement()).toString() + "\n";
     current = current.next;
  }

  return result;

现在它工作并打印,因此错误必须在迭代器中。

这是LinkedList类:

import java.util.*;

import java.util.Iterator;

public class LinkedList10Handout<T> implements ListADT<T>
{
   protected int count;
   protected LinearNode<T> head, tail, current, previous;

   //===========================================================
   //  Creates an empty list.
   //===========================================================
  public LinkedList10Handout() 
  {
      count = 0;
      head = tail = null;
      current = null;
   }  // constructor List

/**************************************************************
// Precondition: head is the head reference of a linked list.
// The list might be empty or it might be non-empty.
//  PostCondition: One node has been added to the list.
//**************************************************************/
    public void InsertFirst(T addData)//*********************************
 {
    LinearNode<T> newnode = new LinearNode<T>(addData, null);

    if (isEmpty())
    {
      head = newnode;
      tail = newnode;
    }    
    else
    { 
      newnode.next = head;
      head = newnode;
    }

    if (current == head.next)
      previous = head;

    count++;
      // LIST REQUIREMENTS:
     // if the list was initially empty, put tail on the list

         //if current was initially at the first node, we must now put previous behind it


 }
/**************************************************************
// this method calls insertAfter method after it finds the node it wants to insert a node after
/**************************************************************/
public boolean Insert(T target, T addData)//*************************
{
   LinearNode<T> find = find(target);
   boolean found = false;

   if (find != null)
   {
      found = true;
      insertAfter(addData);
   }

   // calls find 

 // if  target is found 
 //the method calls insertafter(addData) WHICH DOES THE ACTUAL INSERT 

return found;  // this is just here to allow it to compile
}
/*****************************************************************
// inserts a node at the end of the tail
// CHECKS IF THE LIST IS EMPTY FIRST AND CALLS INSERTFIRST
// ELSE INSERTS ON THE END OF THE LIST
/******************************************************************/
public void insertTail(T target )//******************
{
   if (isEmpty())
      InsertFirst(target);
   else
   {
      LinearNode<T> newnode = new LinearNode<T> (target, null);
      tail.next = newnode;
      tail = newnode;
   }

   count++;
  // INSERT NODE ON THE TAIL
}


   //===========================================================
   // Precondition:  The List is not empty
   //  Removes the first element in the list and returns a reference
   //  to it.  Throws an EmptyListException if the list is empty.
   //===========================================================
   public T removeFirst() throws EmptyCollectionException //*************************
    {
      LinearNode<T> removed = head;

      if (isEmpty())
         throw new EmptyCollectionException("List");     
      else
         head = head.next;  

      // delete the first node
      // return the data;

      count--;

      return removed.getElement();  // this is to get it to compile  - change it
   } // method removeFirst

  /**************************************************************
     *Inserts node with newData after the node current points to. The current
     *node is the same AFTER THE NODE IS INSERTED
     *Should not be used with an empty list. Should not be
     *used when the current node IS NULL.
  /*******Before insertAfter is called current must be pointing to A  node on the list
     **************************************************************/
    public void insertAfter(T newData)//*****************
    { 
      LinearNode<T> newnode = new LinearNode<T>(newData, current.next);

      current.next = newnode;

      if (current == tail)
         tail.next = newnode;

      count++;

     }// close method


/*********************************************************
Finds the first node containing the target data, and returns a
reference to that node. If key is not in the list, null is returned.
*********************************************************/
 public LinearNode<T> find(T target) // WE DID THIS IN CLASS
     {
      if (!isEmpty())
      {  
         for (current = head; current.getElement() != target; current = current.next) 
        // set up a for loop with current initialed to point to what head is pointing to.
          {
            previous = previous.next;
            return current;
         }
         // inside the loop compare the element current is presently pointing to, to target
         // if they are equal return current.element
         // advance previous so that it follows current
      }
        return null;
   }    // close method


   //===========================================================
//  Precondition: Throws an EmptyListException if the list is empty. 
// Throws a  NoSuchElementException if the specified element is not found on the list.
//  PostCondition:Removes the first instance of the specified element from the
//  list if it is found in the list and returns a reference to it.
// SEVERAL SITUATIONS MUST BE HANDLED AS LISTED BELOW
      //===========================================================
        public T remove (T target) throws  EmptyCollectionException, ElementNotFoundException //**************
   {
      if (isEmpty())
         throw new EmptyCollectionException ("List");

      LinearNode<T> find = find(target);

      if (find == null)
         throw new ElementNotFoundException ("List");

      LinearNode<T> removed = new LinearNode<T> (target, null);
               // MAKE SURE TARGET IS ON THE LIST  

               // conditions you have to address:         
        //(1) if there is only one node on the list 
     if (size() == 1)
      head = tail = null;
     else 
      if (find == head)
         removeFirst();
      else
       if (find == tail)
         removeLast();
       else 
       {
         previous.next = current.next;
         current = current.next;
       }

       //(2) if (current points to head node and there is more than one node on the list 



       //  (3) else if current equals tail - we are at the last node - HINT - USE PREVIOUS 


       //(4)IF NONE OF THE ABOVE IS TRUE  we are somewhere in the middle of the list
         // where current is pointing to node to be deleted
        // and previous is right behind it - delete THAT  node 
           count--;         
            // return the removed element
         return  removed.getElement();// this is just to get it to compile

   }  // method remove


    //===========================================================
   //  Removes the last element in the list and returns a reference
   //  to it.  Throws an EmptyListException if the list is empty.
    // CALLS FIND TO LOCATE CURRENT ON THE TAIL NODE 
    // DETERMINES FIRST IF THE THERE IS ONLY ONE NODE AND THEN DELETES THAT
   //===========================================================


   public T removeLast() throws EmptyCollectionException //*******************************
    {
      // remove last node

      if (isEmpty())
         throw new EmptyCollectionException("List");  

      find(tail.getElement());

      previous.next = current.next;
      current = current.next;

      count--;

      return current.getElement();// was result



   } // method removeLast

   //===========================================================
   //  Finds the first instance of the specified element from the
   //  list if it is found in the list and returns true. 
   //  Returns false otherwise.  Calls the find method to find target                                     
   //===========================================================
   public boolean contains (T targetElement) throws  EmptyCollectionException //****************
   {
        if (isEmpty())
         throw new EmptyCollectionException ("List");

      boolean found = false;

      LinearNode<T> find = find(targetElement);

      if (find != null)
         found = true;


      return found;

   }  // method contains 


   //===========================================================
   //  Returns true if the list is empty and false otherwise
   //===========================================================
   public boolean isEmpty() 
    {
      return (count == 0);
   }  // method isEmpty

   //===========================================================
   //  Returns the number of elements in the list.
   //===========================================================
   public int size() //*******************
    {
      // put in code

        return count;  // CHANGE THIS< IT IS TO GET IT TO COMPILE
   }  // method size



 //===========================================================
   //  Returns ... 
   //===========================================================
   public Iterator<T> iterator() 
    {
      return new LinkedIterator<T>(head, count);
   }  // method elements


   //===========================================================
   //  Returns a string representation of the list.
   //===========================================================
      public String toString() //*******************************
    {

      String result = "";
      Iterator<T> iter = iterator();

      while (iter.hasNext()) 
        {

           result += iter + "\n";
        // traverse the list and accumulate the elements in result as you did in DatingService with hobbies         
        }

      return result;

   } // method toString

     //===========================================================
   //  Returns the first element of the list. 
   //===========================================================
   public T first() //***************************
     {

          return head.getElement();  // this is to get it to compile  - change it

   }  // method firstElement

   //===========================================================
   //  Returns the last element of the list. 
   //===========================================================
   public T last()//********************
     {
     // put in code
        return tail.getElement();  // this is to get it to compile  - change it

   }  // method lastElement

}  // class LinkedList


class EmptyCollectionException extends RuntimeException
{
   //-----------------------------------------------------------------
   //  Sets up this exception with an appropriate message.
   //-----------------------------------------------------------------
   public EmptyCollectionException (String collection)
   {
      super ("The " + collection + " is empty.");
   }
}

  class LinkedIterator<T> implements Iterator
    {
       private int count;  // the number of elements in the collection
       private LinearNode<T> current;  // the current position

       //-------------------------------------------------------------
       //  Sets up this iterator using the specified items.
       //-------------------------------------------------------------
       public LinkedIterator (LinearNode<T> collection, int size)
       {
          current = collection;
          count = size;
       }

       //-------------------------------------------------------------
       //  Returns true if this iterator has at least one more element
       //  to deliver in the iteraion.
       //-------------------------------------------------------------
       public boolean hasNext()
       {
          return (current!= null);
       }

       //-------------------------------------------------------------
       //  Returns the next element in the iteration. If there are no
       //  more elements in this itertion, a NoSuchElementException is
       //  thrown.
       //-------------------------------------------------------------
       public T next() //*********************************************
       {
          if (! hasNext())
             throw new NoSuchElementException();

        // put in code
      return current.next.getElement();  // this is to get it to compile  - change it
       }

       //-------------------------------------------------------------
       //  The remove operation is not supported.
       //-------------------------------------------------------------
       public void remove() throws UnsupportedOperationException
       {
          throw new UnsupportedOperationException();
       }
    }

class ElementNotFoundException extends RuntimeException
{
   //-----------------------------------------------------------------
   //  Sets up this exception with an appropriate message.
   //-----------------------------------------------------------------
   public ElementNotFoundException (String collection)
   {
      super ("The target element is not in this " + collection);
   }
}

interface ListADT<T>
{
   //  Removes and returns the first element from this list
   public T removeFirst ();


   //  Removes and returns the specified element from this list
   public T remove (T element);

   //  Returns a reference to the first element on this list
   public T first ();

   //  Returns a reference to the last element on this list
   public T last ();

   //  Returns true if this list contains the specified target element
   public boolean contains (T target);

   //  Returns true if this list contains no elements
   public boolean isEmpty();

   //  Returns the number of elements in this list
   public int size();

   //  Returns an iterator for the elements in this list
   public Iterator<T> iterator();

   //  Returns a string representation of this list
   public String toString();
}

 //************************************************************
 //  LinearNode.java      
 //
 //  Represents a node in a linked list.
 //************************************************************

// YOU MUST PUT IN MORE SETTERS and GETTERS

class LinearNode<T>
 {
    public LinearNode<T> next;
    private T element;

    //---------------------------------------------------------
    //  Creates an empty node.
    //---------------------------------------------------------
    public LinearNode()
    {
       next = null;
       element = null;
    }

    //---------------------------------------------------------
    //  Creates a node storing the specified element.
    //---------------------------------------------------------
    public LinearNode (T elem)
    {
      element = elem;
    }

  //---------------------------------------------------------
    //  Creates a node storing the specified element and link
    //---------------------------------------------------------
    public LinearNode (T elem,  LinearNode<T> next)
    {
      element = elem;
      this.next = next;
    }


   // put in setter and getters for next and element

     //---------------------------------------------------------
    //  Returns the element stored in this node.
    //---------------------------------------------------------
    public T getElement()
    {
       return element;
    }

    //---------------------------------------------------------
    //  Set the element stored in this node.
    //---------------------------------------------------------

    public void setElement (T data)
    {
       element = data;
    }

    //---------------------------------------------------------
    //  Returns the next node.
    //---------------------------------------------------------

    public LinearNode<T> next()
    {
      return next;
    }

    //---------------------------------------------------------
    //  Sets the next node.
    //---------------------------------------------------------

    public void next (LinearNode<T> node)
    {
      next = node;
    }

 }

以下是测试人员类:

public class ProjectTest10

{
public static void main(String args[])
   {

      String B = "B";
       String E = "E";
        String J = "J";

    LinkedList10Handout list = new LinkedList10Handout();
// Code a linked list as pictured in the project specification which contains String B, E and J  and perform the following operations. 
// After each operation print out the list:

// do the appropriate System.out printlns for each operation

          //  1.  insert B into the list

        LinearNode NodeB = new LinearNode (B);
        list.InsertFirst(NodeB.getElement());

       System.out.println("This is a list with B " + list);
         System.out.println();

}}

测试人员课程还有更多,但这样做会阻止它。问题是在insertFirst,我相信,因为当我删除该行时,它显然打印出没有节点的行。

2 个答案:

答案 0 :(得分:0)

LinkedList10Handout中,检查您的toString()功能..

我想你想要这样的东西:

while (iter.hasNext()) 
{
    result += iter.next() + "\n";
}

但是,您的iterator()功能也有问题.. 你需要定义你的迭代器:

new LinkedIterator<T>(beforeHead, count);

而不是:

new LinkedIterator<T>(head, count);

要做到这一点,你需要稍微修改你的代码..祝你好运=)

更新:只需添加一个永远存在的root node(即使列表为空)作为iterator的起点..

此外: 好的,这是一个例子:

import java.util.*;

import java.util.Iterator;

public class LinkedList10Handout<T> implements ListADT<T> {

    protected int count;
    protected LinearNode<T> rootNode;
    protected LinearNode<T> head, tail, current, previous;

   //===========================================================
    //  Creates an empty list.
    //===========================================================
    public LinkedList10Handout() {
        rootNode = new LinearNode();
        count = 0;
        head = tail = null;
        current = null;
    }  // constructor List

    /**
     * ************************************************************
     * // Precondition: head is the head reference of a linked list. // The list
     * might be empty or it might be non-empty. // PostCondition: One node has
     * been added to the list.
//*************************************************************
     */
    public void InsertFirst(T addData)//*********************************
    {
        LinearNode<T> newnode = new LinearNode<T>(addData, null);

        if (isEmpty()) {
            head = newnode;
            rootNode.next = head;
            tail = newnode;

        } else {
            newnode.next = head;
            head = newnode;
        }

        if (current == head.next) {
            previous = head;
        }

        count++;
      // LIST REQUIREMENTS:
        // if the list was initially empty, put tail on the list

         //if current was initially at the first node, we must now put previous behind it
    }

    /**
     * ************************************************************
     * // this method calls insertAfter method after it finds the node it wants
     * to insert a node after
/*************************************************************
     */
    public boolean Insert(T target, T addData)//*************************
    {
        LinearNode<T> find = find(target);
        boolean found = false;

        if (find != null) {
            found = true;
            insertAfter(addData);
        }

   // calls find 
 // if  target is found 
        //the method calls insertafter(addData) WHICH DOES THE ACTUAL INSERT 
        return found;  // this is just here to allow it to compile
    }

    /**
     * ***************************************************************
     * // inserts a node at the end of the tail // CHECKS IF THE LIST IS EMPTY
     * FIRST AND CALLS INSERTFIRST // ELSE INSERTS ON THE END OF THE LIST
/*****************************************************************
     */
    public void insertTail(T target)//******************
    {
        if (isEmpty()) {
            InsertFirst(target);
        } else {
            LinearNode<T> newnode = new LinearNode<T>(target, null);
            tail.next = newnode;
            tail = newnode;
        }

        count++;
  // INSERT NODE ON THE TAIL
    }

   //===========================================================
    // Precondition:  The List is not empty
    //  Removes the first element in the list and returns a reference
    //  to it.  Throws an EmptyListException if the list is empty.
    //===========================================================
    public T removeFirst() throws EmptyCollectionException //*************************
    {
        LinearNode<T> removed = head;

        if (isEmpty()) {
            throw new EmptyCollectionException("List");
        } else {
            head = head.next;
        }

      // delete the first node
        // return the data;
        count--;

        return removed.getElement();  // this is to get it to compile  - change it
    } // method removeFirst

    /**
     * ************************************************************
     * Inserts node with newData after the node current points to. The current
     * node is the same AFTER THE NODE IS INSERTED Should not be used with an
     * empty list. Should not be used when the current node IS NULL.
     * /*******Before insertAfter is called current must be pointing to A node
     * on the list
     *************************************************************
     */
    public void insertAfter(T newData)//*****************
    {
        LinearNode<T> newnode = new LinearNode<T>(newData, current.next);

        current.next = newnode;

        if (current == tail) {
            tail.next = newnode;
        }

        count++;

    }// close method

    /**
     * *******************************************************
     * Finds the first node containing the target data, and returns a reference
     * to that node. If key is not in the list, null is returned.
********************************************************
     */
    public LinearNode<T> find(T target) // WE DID THIS IN CLASS
    {
        if (!isEmpty()) {
            for (current = head; current.getElement() != target; current = current.next) // set up a for loop with current initialed to point to what head is pointing to.
            {
                previous = previous.next;
                return current;
            }
         // inside the loop compare the element current is presently pointing to, to target
            // if they are equal return current.element
            // advance previous so that it follows current
        }
        return null;
    }    // close method

   //===========================================================
//  Precondition: Throws an EmptyListException if the list is empty. 
// Throws a  NoSuchElementException if the specified element is not found on the list.
//  PostCondition:Removes the first instance of the specified element from the
//  list if it is found in the list and returns a reference to it.
// SEVERAL SITUATIONS MUST BE HANDLED AS LISTED BELOW
    //===========================================================
    public T remove(T target) throws EmptyCollectionException, ElementNotFoundException //**************
    {
        if (isEmpty()) {
            throw new EmptyCollectionException("List");
        }

        LinearNode<T> find = find(target);

        if (find == null) {
            throw new ElementNotFoundException("List");
        }

        LinearNode<T> removed = new LinearNode<T>(target, null);
               // MAKE SURE TARGET IS ON THE LIST  

        // conditions you have to address:         
        //(1) if there is only one node on the list 
        if (size() == 1) {
            head = tail = null;
        } else if (find == head) {
            removeFirst();
        } else if (find == tail) {
            removeLast();
        } else {
            previous.next = current.next;
            current = current.next;
        }

       //(2) if (current points to head node and there is more than one node on the list 
       //  (3) else if current equals tail - we are at the last node - HINT - USE PREVIOUS 
       //(4)IF NONE OF THE ABOVE IS TRUE  we are somewhere in the middle of the list
        // where current is pointing to node to be deleted
        // and previous is right behind it - delete THAT  node 
        count--;
        // return the removed element
        return removed.getElement();// this is just to get it to compile

    }  // method remove

    //===========================================================
    //  Removes the last element in the list and returns a reference
    //  to it.  Throws an EmptyListException if the list is empty.
    // CALLS FIND TO LOCATE CURRENT ON THE TAIL NODE 
    // DETERMINES FIRST IF THE THERE IS ONLY ONE NODE AND THEN DELETES THAT
    //===========================================================
    public T removeLast() throws EmptyCollectionException //*******************************
    {
        // remove last node

        if (isEmpty()) {
            throw new EmptyCollectionException("List");
        }

        find(tail.getElement());

        previous.next = current.next;
        current = current.next;

        count--;

        return current.getElement();// was result

    } // method removeLast

   //===========================================================
    //  Finds the first instance of the specified element from the
    //  list if it is found in the list and returns true. 
    //  Returns false otherwise.  Calls the find method to find target                                     
    //===========================================================
    public boolean contains(T targetElement) throws EmptyCollectionException //****************
    {
        if (isEmpty()) {
            throw new EmptyCollectionException("List");
        }

        boolean found = false;

        LinearNode<T> find = find(targetElement);

        if (find != null) {
            found = true;
        }

        return found;

    }  // method contains 

   //===========================================================
    //  Returns true if the list is empty and false otherwise
    //===========================================================
    public boolean isEmpty() {
        return (count == 0);
    }  // method isEmpty

   //===========================================================
    //  Returns the number of elements in the list.
    //===========================================================
    public int size() //*******************
    {
        // put in code

        return count;  // CHANGE THIS< IT IS TO GET IT TO COMPILE
    }  // method size

 //===========================================================
    //  Returns ... 
    //===========================================================
    public Iterator<T> iterator() {
        return new LinkedIterator<T>(rootNode, count);
    }  // method elements

   //===========================================================
    //  Returns a string representation of the list.
    //===========================================================
    public String toString() //*******************************
    {

        String result = "";
        Iterator<T> iter = iterator();

        while (iter.hasNext()) {
            result += iter.next().toString() + "\n";

            // traverse the list and accumulate the elements in result as you did in DatingService with hobbies         
        }

        return result;

    } // method toString

     //===========================================================
    //  Returns the first element of the list. 
    //===========================================================
    public T first() //***************************
    {

        return head.getElement();  // this is to get it to compile  - change it

    }  // method firstElement

   //===========================================================
    //  Returns the last element of the list. 
    //===========================================================
    public T last()//********************
    {
        // put in code
        return tail.getElement();  // this is to get it to compile  - change it

    }  // method lastElement

}  // class LinkedList

class EmptyCollectionException extends RuntimeException {
   //-----------------------------------------------------------------
    //  Sets up this exception with an appropriate message.
    //-----------------------------------------------------------------
    public EmptyCollectionException(String collection) {
        super("The " + collection + " is empty.");
    }
}

class LinkedIterator<T> implements Iterator {

    private int count;  // the number of elements in the collection
    private LinearNode<T> current;  // the current position

       //-------------------------------------------------------------
    //  Sets up this iterator using the specified items.
    //-------------------------------------------------------------
    public LinkedIterator(LinearNode<T> collection, int size) {
        current = collection;
        count = size;
    }

       //-------------------------------------------------------------
    //  Returns true if this iterator has at least one more element
    //  to deliver in the iteraion.
    //-------------------------------------------------------------
    public boolean hasNext() {
        return (current.next != null);
    }

       //-------------------------------------------------------------
    //  Returns the next element in the iteration. If there are no
    //  more elements in this itertion, a NoSuchElementException is
    //  thrown.
    //-------------------------------------------------------------
    public T next() //*********************************************
    {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        current = current.next;

        // put in code
        return current.getElement();  // this is to get it to compile  - change it
    }

       //-------------------------------------------------------------
    //  The remove operation is not supported.
    //-------------------------------------------------------------
    public void remove() throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }
}

class ElementNotFoundException extends RuntimeException {
   //-----------------------------------------------------------------
    //  Sets up this exception with an appropriate message.
    //-----------------------------------------------------------------
    public ElementNotFoundException(String collection) {
        super("The target element is not in this " + collection);
    }
}

interface ListADT<T> {

    //  Removes and returns the first element from this list
    public T removeFirst();

    //  Removes and returns the specified element from this list
    public T remove(T element);

    //  Returns a reference to the first element on this list
    public T first();

    //  Returns a reference to the last element on this list
    public T last();

    //  Returns true if this list contains the specified target element
    public boolean contains(T target);

    //  Returns true if this list contains no elements
    public boolean isEmpty();

    //  Returns the number of elements in this list
    public int size();

    //  Returns an iterator for the elements in this list
    public Iterator<T> iterator();

    //  Returns a string representation of this list
    public String toString();
}

 //************************************************************
//  LinearNode.java      
//
//  Represents a node in a linked list.
//************************************************************
// YOU MUST PUT IN MORE SETTERS and GETTERS
class LinearNode<T> {

    public LinearNode<T> next;
    private T element;

    //---------------------------------------------------------
    //  Creates an empty node.
    //---------------------------------------------------------
    public LinearNode() {
        next = null;
        element = null;
    }

    //---------------------------------------------------------
    //  Creates a node storing the specified element.
    //---------------------------------------------------------
    public LinearNode(T elem) {
        element = elem;
    }

    //---------------------------------------------------------
    //  Creates a node storing the specified element and link
    //---------------------------------------------------------
    public LinearNode(T elem, LinearNode<T> next) {
        element = elem;
        this.next = next;
    }

   // put in setter and getters for next and element
    //---------------------------------------------------------
    //  Returns the element stored in this node.
    //---------------------------------------------------------
    public T getElement() {
        return element;
    }

    //---------------------------------------------------------
    //  Set the element stored in this node.
    //---------------------------------------------------------
    public void setElement(T data) {
        element = data;
    }

    //---------------------------------------------------------
    //  Returns the next node.
    //---------------------------------------------------------
    public LinearNode<T> next() {
        return next;
    }

    //---------------------------------------------------------
    //  Sets the next node.
    //---------------------------------------------------------
    public void next(LinearNode<T> node) {
        next = node;
    }

}

答案 1 :(得分:-1)

 list.InsertFirst(NodeB.getElement());

您是否尝试插入Node本身或Node.getElement?