链表到达列表末尾时

时间:2014-09-26 02:07:19

标签: java singly-linked-list

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

我正在为现有的链表添加方法。

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

1 个答案:

答案 0 :(得分:3)

我认为如果左侧部分为 false ,则错过&&运算符的右侧部分未被评估的点。或者java documentation说:

  

这些运营商展示了&#34;短路&#34;行为,这意味着仅在需要时才评估第二个操作数。

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


在你的情况下:

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

如果nodeValue为空,nodeValue.getData()会在检查NullPointerException之前抛出nodeValue != null
但如果你这样做:

 (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()) )
{
//...