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

问题描述 投票:0回答:1

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

  1. 项目清单

公共静态类Stack {

     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;
        }
        }

}

//客户端测试代码

public static void main(String[] args) {


        StdOut.print("Type the linked list:");
        Stack list = new Stack();
        int index;
        String in=StdIn.readLine();
        for(int i=0;i<=in.length();i++)
        {
         list.push(in);
        }
        StdOut.print("Type the index to be deleted:");
        index=StdIn.readInt();
        StdOut.println("Before deleting element at "+ index);
        StdOut.println(in);



        StdOut.println("After deleting element at "+ index);
        StdOut.print(list.delete(index,list).item);


}

}

java linked-list
1个回答
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)

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.