排序集代码有什么问题?我的输出应该和样品相符

vatpfxk5  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(235)

有人能帮我找出我的代码有什么问题吗?当我运行它时,只显示第一个输入数字(它不创建排序列表),delete命令不起作用,exists命令中的'true''false'不显示。我的输出应该与我在最后给出的样本相匹配。
为了使代码正常工作,我必须填写的区域是todododo符号后面的区域,即44-61、75-83、97-105。我不知道我在这些方面哪里出了问题,为什么它不能正常工作,以提供所需的输出?

import java.util.Scanner;

// Defines the a Sorted Set collection and implements a driver program in main
public class SortedSet {
    // Define a basic element of a linked list
    private class LinkedNode {
        int x;  // Value stored in the node
        LinkedNode next;  // Reference to the next node in the list
    }

LinkedNode front = null;  // Reference to the front of the singly linked list

// Adds the integer x to the collection.
// The resulting collection is sorted in increasing order and
// does not contain any duplicate values.
public void add(int x) {
    // Initialize a new node to be added to the collection
    LinkedNode newNode = new LinkedNode();
    LinkedNode cur = front;
    newNode.x = x;

    // Check if list is empty
    if (cur == null) {
        front = newNode;
    } 
    // If list is not empty, check if node should be placed in front
    else if (front != null) {
        if (newNode.x < front.x) {
            newNode.next = front;
            front = newNode;
        }

        // If not in front, check for the middle or the end, or duplicate.
        else {
            // <TODO><TODO><TODO> 
            LinkedNode temp = cur;
            LinkedNode prev = cur;
            int middle = x;
            while (temp != null) {
                if(temp.x > newNode.x) {
                    middle = 1;
                    newNode.next = temp;
                    prev.next = newNode;
                }
                prev = temp;
                temp = temp.next;
                }
            if (middle == 0) {
                prev = newNode;
                }
            }
        }
    }

// Deletes the integer x from the sorted set.
// The remaining collection remains sorted and without duplicates.
public void delete(int x){
    // Declare a new reference and initialize it to the front of the list
    LinkedNode cur = front;

    // Check if list is empty
    if (front == null) {
        System.out.print("There is nothing to delete!");
    } else {  // Not empty
        // Go through list, checking whether node is in the list, and delete if found
        // <TODO><TODO><TODO>
        LinkedNode prev = new LinkedNode();
        while (cur.x != x && cur != null) {
            prev = cur;
            cur = cur.next;
            }
        if (cur != null)
            prev.next = cur.next;
        }
    }

// Returns true if the integer x exists in the sorted set and false otherwise.
public void exists(int x) {
    // Declare a new reference and initialize it to the front of the list
    LinkedNode cur = front;

    // Check if list is empty.
    if (front == null) {
        System.out.println("false");
    }

    // If not empty, check for the node.
    // <TODO><TODO><TODO>
    else {
        while (cur != null) {
            if (cur.x==x)
                return;
            cur=cur.next;
            }
        return;
    }
}

// Returns a string representing the sorted set as a space separated list.
public String toString() {
    String s = "";

    LinkedNode cur = front;     
    while (cur!=null) {
        s+= cur.x + " ";
        cur = cur.next;
    }

    return s;
}

// Driver method
public static void main(String[] args) {
    // Declare variables
    SortedSet sortedSet = new SortedSet();
    Scanner scan = new Scanner(System.in);
    String[] tokens;
    String command;
    int num;

    // Print header info
    System.out.println("Programming Fundamentals\n"
            + "NAME: Andres Reyes\n"
            + "PROGRAMMING ASSIGNMENT 4\n");

    // Enter command loop
    while (true) {
        // Prompt the user for a command
        System.out.print("Enter command: ");
        String input = scan.nextLine();

        // Parse input
        if (input.equals("q")) break;  // user quits
        tokens = input.split("\\s");
        if (tokens.length < 2) continue; // invalid input
        command = tokens[0];
        num = Integer.parseInt(tokens[1]);

        // Execute command
        if (command.equals("add")){
            sortedSet.add(num);
            System.out.println(sortedSet);
        } else if (command.equals("del")) {
            sortedSet.delete(num);
            System.out.println(sortedSet);
        } else if (command.equals("exists")) {
            sortedSet.exists(num);
        } else {
            System.out.print("Command does not exist");
        }
    }

    System.out.println("\nGood bye!");
}

}

6qqygrtg

6qqygrtg1#

我可以给你一些提示。我看到这段代码的主要问题是,您确实需要对linkedlist的开头(head)进行引用,这是打印列表并检查重复项的唯一方法。
以下内容应添加到您的类中

LinkedList head = null; //start of the list

然后必须更新tostring(),否则无论做什么,都无法打印列表中正确的元素。试试这个:

public String toString(){
    StringBuilder output = new StringBuilder();
    LinkedNode current = head;
    while(current != null){
        output.append(current.x).append(" ");
        current = current.next;
    }
    return output.toString();
}

在循环中附加到字符串时必须非常小心,因为字符串是不可变的。每次添加到列表时,您都在创建一个新字符串。相反,使用 StringBuilder .

//s+= cur.x + " ";

add方法应处理以下情况:
案例1:列表为空:(不要忘记将ref设置为head)
案例2:新元素比列表前面的好
案例3:新元素小于当前头
情况4:新元素小于当前值,大于头

2o7dmzc5

2o7dmzc52#

我在add函数中做了以下更改,他们让它为我工作:

// If not in front, check for the middle or the end, or duplicate.
     else {
         // <TODO><TODO><TODO> 
         LinkedNode temp = cur.next; // start at cur.next as your temp-variable
         LinkedNode prev = cur;
         int middle = 0; // set middle to 0
         while (temp != null) {
             if(temp.x > newNode.x) {
                 middle = 1;
                 newNode.next = temp;
                 prev.next = newNode;
             }
             prev = temp;
             temp = temp.next;
          }
         if (middle == 0) {
             // add node to the end
             prev.next = newNode;
          }
         }
     }

必须从cur.next开始作为临时变量。
据我所知,您还没有检查列表中是否有重复的值。
编辑:我没有使用exists方法,它目前没有给你任何输出。问题很简单,就是在检查列表中是否存在值时生成任何输出。您可以编写一个system.out.print,在找到值的情况下打印“true”,在没有找到值的情况下打印“false”。或者将exists函数的返回类型改为boolean,根据结果返回一个boolean并打印返回值。
它还可以帮助您可视化一个链表,以理解为什么必须将temp变量更改为cur.next。我想https://www.tutorialspoint.com/data_structures_algorithms/linked_lists_algorithm.htm 很好地解释了插入过程。

相关问题