我为特定索引(Java)的链表中的节点编写了一个删除方法,但它对列表没有任何更改?

时间:2018-10-02 17:44:56

标签: java linked-list

代码不对输出进行任何更改,仅重印了原始的链表,我不知道问题出在我的删除方法还是我在堆栈中使用的访问说明符。

  1. 列表项

公共静态类堆栈 {

MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();

List<string> To = new List<string>();
To.Add("email1@gmail.com");
To.Add("email1@gmail.com");

foreach (var item in To)
{
     mail.To.Add(to);
}

SmtpServer.Send(mail);

}

//客户端测试代码

     Node first; *// newest node added*
    private int size;
     class Node
    {  
           String item;
           Node next; 

    }
    public Node delete(int index,Stack list)
    {  

        if (list.first== null) {
            return null;
        } else if (index == 0) 
        {
            return list.first.next;
        }
        else
        {
            Node n = list.first;
            for (int i = 0; i < index - 1; i++) 
            {
                n = n.next;
                if(i==index)
                n.next = n.next.next;//skips over the existing element

            }
            return list.first;
        }
        }

}

1 个答案:

答案 0 :(得分:0)

在delete()函数中,您返回的是list.first,它指向列表的头节点,而不是Node first* //newest node added*,对吗?我认为您应该在删除任务完成后从函数返回,而不是返回nullnode

此外,当您遍历最终else语句中的列表时,应将n = n.next;行移至索引检查下方。

您的delete()函数如下所示:

public Node delete(int index,Stack list)
{  

    if (list.first== null) 
    {
        return;
    } else if (index == 0) 
    {
        return;
    }
    else
    {
        Node n = list.first;
        for (int i = 0; i < index; i++) 
        {
            //If the next Node of the current node is +1 the current index
            if(i+1==index)
            {
                n.next = n.next.next;//skips over the existing element
                return;
            }

            n = n.next;

        }
        return;
    }
 }

然后:

list.delete(index,list).item; //call the delete function
StdOut.println("After deleting element at "+ index);
list.print(); //Print the list using its print function (assuming you have one)

我希望这会有所帮助!