有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我不能通过将节点分配到下一个节点来从循环链表中删除节点?

该程序接受用户数据(名称)并在屏幕上输出信息。然后询问用户要从链表中删除的名称

我在删除程序时遇到困难。我似乎无法删除节点,因为我正在用“下一个”和“上一个”重新激活一个错误(见下文)

public static void main (String str[]) throws IOException
    {
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));        

        Node node, head, tail; // node is where string data is kept

        String name, delete;
        int count = 0;

        head = null; // initialize the head  and tail to null
        tail = null;


        System.out.print ("Enter a name. Type q to end inputting.");

        name = stdin.readLine ();

        node = new Node (name);
        node.next = head;
        head = node;
        tail = node;

        contestant = null;

        do // loop to create new nodes for the linked list using user data
        {

            System.out.print ("Enter a name. Type q to end.");
            name = stdin.readLine ();

            // create a new node if the user has not decided to quit
            if (!contestant.equals ("q"))
            {
                node = new Node (name);
                node.next = head;
                count++;
                head = node;  // update the head to point to the new front of the list

            }
        }
        while (!contestant.equals ("q"));  // loop continues until "q" selected      

        System.out.println ();


        do // display contestants
        {
            System.out.println (node.data);
            node = node.next;
        }
        while (node != null);  // loop until the end of lists is reached

        //////////////////////////////////////////Delete///////////////////////////////////////////


        boolean Delete; // check to see if deleted

        Node listNode; // node to delete

        System.out.println ("Enter a node to be removed:");
        delete = stdin.readLine ();

        listNode = new Node (delete);

        Node temp = listNode;

        do
        {
            if (temp.listNode () == node) 
            {
                node.prev = temp.previous (); 
                node.next = temp.next (); 

                if (prev != listNode.next) 
                {
                    prev.next () = next; 
                    next.previous () = prev; // removed 
                    return true; 
                }

                else
                {
                    return false; // only one node 
                }
                temp = temp.next (); 
            }
        }
        while (temp != listNode);   // couldnt remove
        return false; 
}
}

节点类:

public class Node
{
    Node next, prev;
    String data;

    public Node (String data)
    {
        this.data = data;
    }
}

共 (0) 个答案