我添加了评论以解释我的逻辑
public void removeStrin(String name) throws IllegalArgumentException {
// If the name is equal to null throw an exception
if(name == null) {
throw new IllegalArgumentException();
}
//set the removeTempString to the head
Game Rem = head;
答案 0 :(得分:1)
执行此类操作,设置previous.nxt = nodetobedeleted.next;
并且空的和notobedeleted可能有的资源。
public void removeGame(String name) throws IllegalArgumentException {
// If the name is equal to null throw an exception
if(name == null) {
throw new IllegalArgumentException();
}
//set the removeTempString to the head
Game removeTempString = head;
Game prev = null;
//while it is not null
while(removeTempString != null) {
//if the removeTempString.name equals the String name
if(removeTempString.name.equals(name)){
if(prev != null){
prev.next = removeTempString.next;
}
}
// set prev to current`enter code here`
prev = removeTempString;
// to iterate set it to next node in list
removeTempString = removeTempString.next;//the next pointer you have
}
答案 1 :(得分:0)
总的来说,你的问题要求查找和删除链表中的节点而不管它在链中的位置,因此它可能是第一个,最后一个或中间的某个位置。
下面提供了一些关于这个问题的安全假设。
游戏类具有以下结构。
class Game{
public String name;
public Game prev;
public Game next;
}
head 对象已在包含类中定义。
removeGame()方法必须在以下三组方案中进行编码,这些方案将隐式处理节点删除。如果它返回了某些内容,您可以获得成功删除的信息。这里它返回布尔值。它实际上基于主题,即需要删除的主题节点必须成为垃圾收集的候选者。
public boolean removeGame(Game txt)
{
if(txt==null)return false;
Game itr = head;
//if its header
if(itr.name.equals(txt.name))
{
Game newHead = head.next;
head=newHead;
//The previous header hence gets derefrenced and becomes a candidate of garbage collection
return true;
}
//if its midway or end
itr = head.next;
while(itr!=null){
Game subjectNode = itr;
if(subjectNode.name.equals(txt.name))
{
Game newPrev = subjectNode.prev;
Game newNext = subjectNode.next;
newPrev.next = subjectNode.next;
newNext.prev= subjectNode.prev;
subjectNode=null;
//This makes it derefrenced and hence subject to garbage collections after refrence swaps.
return true;
}
itr = itr.next;
}
return false;
}
此外,由于您正在进行Java实现,因此更喜欢使用java的util包的 LinkedList 类来拟合您的场景。
答案 2 :(得分:0)
尝试使用此逻辑,它适用于两种方式
public Object delete(Object key) // works
{
Node prev = null;
Node curr = top;
Object result = null;
//search for the key
while((curr != null) && (!curr.getData().equals(key)))
{
prev = curr;
curr = curr.getNext();
}
//found the item we are looking for!
if ( curr != null )
{
//wait! is the item we are looking for the first element in the list?
if ( prev != null )//nah, it's not
{
prev.setNext(curr.getNext());
}else //yes! it is
{
top = curr.getNext();
}
}
return result;
}