如何删除链接列表中的第一个节点? [英] How do you remove the first Node in a Linked List?

查看:101
本文介绍了如何删除链接列表中的第一个节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,所以我要检查链接列表类中的一些方法,并且从链接列表中删除节点时遇到逻辑错误.当我在removeLast()方法中也遇到错误时,我正在使用removeFirst()方法.问题在于,两者都删除了列表中的最后一项.不知道为什么,但是这是我的代码.

Sup guys so I'm going over a few of my methods in my Linked List class and I'm getting a logical error when removing a node from a linked list. I was working on my removeFirst() method when I then encountered a error in my removeLast() method as well. The problem is that both remove the last item in the list. not sure why but here is my code.

删除第一个节点

public T removeFirst() throws EmptyCollectionException
{
 // Checking to see if the List is empty or not
    if ( isEmpty() )
        throw new EmptyCollectionException("LinkedList");

    Node < T > temp  = contents;

    T  next = contents.getNext().getItem();

    contents = new Node ( next, contents );
    count--;

    return temp.getItem();
}



删除最后一个节点



Remove Last Node

public T removeLast() // fixed
{
 // Checking to see if the List is empty or not
    if (isEmpty())
        throw new EmptyCollectionException("LinkedList");

    // Node<T> temp = contents;
    Node<T> current = contents;  
    Node<T> prev = null;        

    while (current.getNext() != null) 
    {
        prev = current; 
        current = current.getNext();
    } 

    prev.setNext(null); 

    count--;

    return current.getItem();

}

我环顾了已经发布的问题,但似乎找不到所需的答案.
我知道一个节点至少有两个值
一个保存数据,另一个保存对下一个节点的引用

我认为这就是第一个.但是,当我一个接一个地调用方法时,它们都摆脱了最后一个节点. Idk我将查看我的代码,并在必要时更新此问题.但是,你们能看到我要去哪里哪里,并指出正确的方向吗?谢谢.

I've looked around the questions already posted but I can't seem to find the answer I'm looking for.
I Know that a node has at least two values
one to hold the data and another to hold the reference to the next node

That's what I think is going on for the first one. But when I call the methods one after another they both get rid off the last node. Idk I will look over my code and update this question if necessary. But can you guys see where I'm going wrong and point me in the right direction. Thank you.

推荐答案

如果您有列表A-> B-> C,则A是列表的开头(内容"),为了将其删除,只需将指针前进到B,即列表中的下一个节点:

If you have a list A->B->C, A being the head ("contents") of your list, in order to remove it, you simply have to advance the pointer to B, i.e. the next node in your list:

public T removeFirst() throws EmptyCollectionException {
    // Checking to see if the List is empty or not
    if ( isEmpty() )
        throw new EmptyCollectionException("LinkedList");

    Node<T> first = contents;

    contents = contents.getNext();
    count--;

    return first.getItem();
}

由于还需要返回与第一个节点关联的数据,因此需要保留对其的临时引用. (我称它为first)

Since you also need to return the data associated with the first node, you need to keep a temporary reference to it. (I called it first)

这篇关于如何删除链接列表中的第一个节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆