//在链表中查找关键字的方法publicvoidfind(int key)
{
Link current=firstNode;
while(true)
{
if(current.getData1()==key)
{
break;
}
else
{
current=current.nodeNext;
if(current==null)
break;
}
}
if(current!=null)
{
System.out.println("find it");
System.out.println("key is "+current.getData1()+" and the other data is "+current.getData2());
}else
{
System.out.println("we can not find it");
}
}
测试一下:
list.find(2000);
输出:we can not find it
list.find(6);
输出:find it
key is 6 and the other data is 6.0
关于关键数据项的删除
这种删除从链表head部开始删除较麻烦,需要引入privious Link对象。
//从链表中删除关键字 指定节点的删除public Link removeKey(int key)
{
Link privious=firstNode;
Link current=firstNode;
while(current.getData1()!=key)//没找到key 指针移动
{
privious=current;
current=current.nodeNext;
if(current==null)
break;
}
//找到了keyif(current==firstNode)
{
firstNode=firstNode.nodeNext;
}
else
{
privious.nodeNext=current.nodeNext;
}
return current;
}