有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java linkedlist到达列表末尾时

public class LList2<T> implements ListInterface<T>
{
private Node firstNode; // head reference to first node
private Node lastNode;  // tail reference to last node
private int  numberOfEntries;

public LList2()
{
    clear();
} // end default constructor

public final void clear() // NOTICE clear is not final in interface and that is OK
{
    firstNode = null;
    lastNode = null;
    numberOfEntries = 0;
} // end clear

public void add(T newEntry)       // OutOfMemoryError possible
{
    Node newNode = new Node(newEntry); // create new node

    if (isEmpty())
        firstNode = newNode;
    else
        lastNode.setNextNode(newNode);

    lastNode = newNode;
    numberOfEntries++;
}  // end add

public boolean add(int newPosition, T newEntry)  // OutOfMemoryError possible                                                    
{
  boolean isSuccessful = true;

  if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) 
  {
     Node newNode = new Node(newEntry);

     if (isEmpty())
     {
        firstNode = newNode;
        lastNode = newNode;
     }
     else if (newPosition == 1)
     {
        newNode.setNextNode(firstNode);
        firstNode = newNode;
     }
     else if (newPosition == numberOfEntries + 1)
     {
        lastNode.setNextNode(newNode);
        lastNode = newNode;
     } 
     else
     {
        Node nodeBefore = getNodeAt(newPosition - 1);
        Node nodeAfter = nodeBefore.getNextNode();
        newNode.setNextNode(nodeAfter);
        nodeBefore.setNextNode(newNode);
     } // end if        
     numberOfEntries++;
  }
  else
     isSuccessful = false;

   return isSuccessful;
} // end add

public T remove(int givenPosition)
{
  T result = null;                 // return value

  if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
  {
     assert !isEmpty();
     if (givenPosition == 1)        // case 1: remove first entry
     {
        result = firstNode.getData();     // save entry to be removed 
        firstNode = firstNode.getNextNode();
        if (numberOfEntries == 1)
           lastNode = null; // solitary entry was removed
        }
        else                           // case 2: givenPosition > 1
        {
           Node nodeBefore = getNodeAt(givenPosition - 1);
           Node nodeToRemove = nodeBefore.getNextNode();
           Node nodeAfter = nodeToRemove.getNextNode();
           nodeBefore.setNextNode(nodeAfter);  // disconnect the node to be removed
           result = nodeToRemove.getData();  // save entry to be removed

           if (givenPosition == numberOfEntries)
              lastNode = nodeBefore; // last node was removed
     } // end if

     numberOfEntries--;
  } // end if

  return result;                   // return removed entry, or 
                                  // null if operation fails
} // end remove

public boolean replace(int givenPosition, T newEntry)
{
    boolean isSuccessful = true;

  if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
  {   
    assert !isEmpty();

        Node desiredNode = getNodeAt(givenPosition);
        desiredNode.setData(newEntry);
  }    
    else
        isSuccessful = false;

    return isSuccessful;
} // end replace

public T getEntry(int givenPosition)
{
  T result = null;  // result to return

    if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
    {
        assert !isEmpty();
     result = getNodeAt(givenPosition).getData();
    } // end if

  return result;
} // end getEntry

public boolean contains(T anEntry)
{
    boolean found = false;
    Node currentNode = firstNode;

    while (!found && (currentNode != null))
    {
        if (anEntry.equals(currentNode.getData()))
            found = true;
        else
            currentNode = currentNode.getNextNode();
    } // end while

    return found;
} // end contains

public int getLength()
{
   return numberOfEntries;
} // end getLength

public boolean isEmpty()
{
    boolean result;

    if (numberOfEntries == 0) // or getLength() == 0
    {
        assert firstNode == null;
        result = true;
    }
    else
    {
        assert firstNode != null;
        result = false;
    } // end if

    return result;
} // end isEmpty

public T[] toArray()
{
  // the cast is safe because the new array contains null entries
  @SuppressWarnings("unchecked")
  T[] result = (T[])new Object[numberOfEntries]; // warning: [unchecked] unchecked cast

  int index = 0;
  Node currentNode = firstNode;
  while ((index < numberOfEntries) && (currentNode != null))
  { 
    result[index] = currentNode.getData();
    currentNode = currentNode.getNextNode();
   index++; 
  } // end while

 return result;
} // end toArray

// Returns a reference to the node at a given position.
// Precondition:  List is not empty; 1 <= givenPosition <= numberOfEntries. 
private Node getNodeAt(int givenPosition)
{
    assert (firstNode != null) && (1 <= givenPosition) && (givenPosition <=       numberOfEntries);
    Node currentNode = firstNode;

  if (givenPosition == numberOfEntries)
     currentNode = lastNode;
  else if (givenPosition > 1)      // traverse the chain to locate the desired node
    {
     for (int counter = 1; counter < givenPosition; counter++)
        currentNode = currentNode.getNextNode();
    } // end if

    assert currentNode != null;
    return currentNode;
} // end getNodeAt

public int getIndex(T item)
{
   int counter = 1;
   int index=1;

Node nodeValue = firstNode;

System.out.println("The index is ");

while((index <= numberOfEntries) && (nodeValue != null))
{

nodeValue = nodeValue.getNextNode();
counter++;
if(nodeValue==null)
{
    return -1;
}
}
if(item.equals(nodeValue.getData()))
{
    return counter;
}
else if ((1 < index) || (nodeValue==null)) //((index > numberOfEntries) && (nodeValue==null))
{
    return -1;
}

} 


 public int removeEvery(T item)
 {
    Node tempNode = firstNode;
    int removeItemCounter = 0;
    int index =1; 
    System.out.println("remove this many item ");
    while ((index <= numberOfEntries) && (tempNode != null))
    {
            if(item.equals(tempNode.getData()))
            {

                remove(index);

                removeItemCounter++;    
            }
            tempNode = tempNode.getNextNode();
            index++;
    } 
  return removeItemCounter;
 }

 ////Question 2

 public boolean equals(Object others)
 {
 Node tempNode = firstNode;
 Node otherNode = ((LList2)others).firstNode;
 int index = 1;
 if((others instanceof LList2) && (numberOfEntries == ((LList2) others).getLength())) //
 {
    while((tempNode.getData()).equals(otherNode.getData()) 
            && (index < numberOfEntries) 
            && (tempNode != null) && (otherNode != null))
    {
        tempNode = tempNode.getNextNode();
        otherNode = otherNode.getNextNode();
        index++;
        System.out.println((tempNode.getData()).equals(otherNode.getData()));
    }
    if(tempNode.getData().equals(otherNode.getData()))
    {
        return false; 
    }
    else//tempNode!=otherNode
    {
        return true;
    }
 }
 else
 return false;
 }
  End of Question 2////////////////////////////////////////////////



  private class Node 
  {
    private T data;  // data portion
    private Node next;  // next to next node

    private Node(T dataPortion)//  PRIVATE or PUBLIC is OK
    {
        data = dataPortion;
        next = null;    
    } // end constructor

    private Node(T dataPortion, Node nextNode)//  PRIVATE or PUBLIC is OK
    {
        data = dataPortion;
        next = nextNode;    
    } // end constructor

    private T getData()
    {
        return data;
    } // end getData

    private void setData(T newData)
    {
        data = newData;
    } // end setData

    private Node getNextNode()
    {
        return next;
    } // end getNextNode

    private void setNextNode(Node nextNode)
    {
        next = nextNode;
    } // end setNextNode
} // end Node
} // end LList2

nodeValue = nodeValue.getNextNode();
System.out.println(nodeValue.getData());
counter++;
}
if(item.equals(nodeValue.getData()))
{
    return counter;
}
//need help here;)
else //((index > numberOfEntries) && (nodeValue==null))
{
    return -1;
}
}   



public static void main(String[] args)
{
LList2<Integer> myList = new LList2<Integer>();
myList.add(14);
myList.add(8);
myList.add(8);
myList.add(22);
myList.add(4);
myList.add(10);


System.out.println(myList.getIndex(11));
}

我正在向已经存在的linkedlist添加一个方法

问题2) 与问题1非常相似。当我比较两个对象时,两列上的每一列都应该相等。当我到达列表末尾时,如果列表中的每一列相等,我如何使程序返回true


共 (1) 个答案

  1. # 1 楼答案

    我想你错过了一个点,如果左半部分是false,那么&&操作符的右半部分就不会被计算。或者正如java documentation所说:

    These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

    例如,在isBlue() && isBig()中,如果isBlue()返回false,则不会调用isBig()函数


    就你而言:

    !(item.equals(nodeValue.getData())) && (index <= numberOfEntries) && (nodeValue != null)
    

    如果nodeValue为空,则nodeValue.getData()将在选中nodeValue != null之前抛出NullPointerException
    但如果你这么做了:

     (nodeValue != null) && (index <= numberOfEntries) && !(item.equals(nodeValue.getData()))
    

    然后nodeValue != null将为false,并且nodeValue.getData()将不会被计算(并且不会引发异常)


    同样,你也可以这样做:

    if((nodeValue != null) && item.equals(nodeValue.getData()))
    {
        return counter;
    }
    //...
    

    while( (tempNode != null) && (otherNode != null) 
            && (index < numberOfEntries)
            && (tempNode.getData()).equals(otherNode.getData()) )
    {
    //...