1

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

我的程序涉及删除时遇到困难。我似乎无法删除节点,因为我正在使用“下一个”和“上一个”(见下文)恢复错误。

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

0 回答 0