oldVal()方法这将获得删除节点所需的正确的if,else-if或else语句,但后来我总是得到一个零点异常我将它与类似的代码进行了比较,似乎无法找到这有什么问题。
请帮助:
enter code here// ***************************************************************
// DoubleLinked.java
//
// A class using a doubly linked list to represent a list of integers.
//
// ***************************************************************
public class DoubleLinked
{
private int size=0;
private IntNode list;
// ----------------------------------------------
// Constructor -- initializes list
// ----------------------------------------------
public DoubleLinked()
{
list = null;
}
// ----------------------------------------------
// Prints the list elements
// ----------------------------------------------
public void print()
{
for (IntNode temp = list; temp != null; temp = temp.next)
System.out.println(temp.val);
}
// ----------------------------------------------
// Adds new element to front of list
// ----------------------------------------------
public void addToFront(int val)
{
IntNode newNode = new IntNode(val);
newNode.next = list;
if (list != null)
list.prev = newNode;
list = newNode;
size++;
}
public void addToEnd(int val)
{
IntNode newNode = new IntNode(val);
IntNode current;
if (list == null)
{list= newNode;}
else
{
current=list;
while(current.next != null)
current = current.next;
current.next = newNode;
}
size++;
}
public void removeFirst()
{
IntNode test = list;
if (test == null){System.out.println("your list is emty"); size++;}
else if (list != null) { // list might be empty
IntNode temp = list.prev;
if(list.next==null && list.prev==null) {
list=null;
}
else {
list.next.prev = null;
list = list.next;
}
}
size--;
}
public void removeLast()
{
IntNode test = list;
if (test == null){System.out.println("your list is emty"); size++;}
else if(list.next==null && list.prev==null)
{
list=null;
}
else if (list != null){
IntNode current=list;
while(current.next.next != null)
current = current.next;
current.next=null;
}
size--;
}
public void oldVal(int val)
{
IntNode temp=list;
for (int i = 0; i < this.size; i++)
{
if (temp.val != val)
temp= temp.next;
else{
if (temp.prev == null)
{
list=list.next;
}
if (temp.next == null)
{
temp.prev.next=null;
}
else
{
temp.prev.next=temp.next;
temp.next.prev=temp.prev;
}
size--;
break;
}
}}
//***************************************************************
// An inner class that represents a list element.
//***************************************************************
class IntNode
{
public int val;
public IntNode next;
public IntNode prev;
public IntNode(int val)
{
this.val = val;
this.next = null;
this.prev = null;
}
}}