Java test questions - data structure test questions

Data structure test questions

Here, according to some data structure questions, I share my ideas and source code for you to exchange and learn! All ideas and codes in this article are for reference only. If there is anything wrong, please correct it!

The following questions are for reference

1, Return the index of the list as required

Example: define a method listtest (ArrayList, list, string name) to return the index of the first occurrence of name in the list. If name does not appear, return - 1.
Idea: use arraylist to define a table, recycle and find the contents in it, return the serial number if it exists, and return - 1 if it does not exist

The code is as follows (example):

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ArrayList<String> data = new ArrayList<>();//Define a data table
        data.add("Zhang San");
        data.add("Li Si");
        data.add("Wang Er Ma Zi");
        data.add("Zhang San");
        String name = input.nextLine();
        int a = listTest(data, name);
        System.out.println(a);
    }
    /**
     *
     * @param list data sheet
     * @param name Name to query
     * @return Returns the index of the first occurrence of name in the list. If name does not appear, returns - 1
     */
    public static int listTest(ArrayList<String> list, String name) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(name)) {
                return i;
            }
        }
        return -1;
    }

The operation screenshot is as follows:

2, Delete the duplicate elements in the list, and print all the elements in the list with iterators and enhanced for loops respectively

Example: the known array stores a batch of QQ numbers with a length of 5-11 bits, String[] strs = {"10001", "10086", "12347806666", "45612378901", "10001", "12347806666"}. Store all QQ numbers in the array in the LinkedList, delete duplicate elements in the list, and print all elements in the list with iterators and enhanced for loops respectively.
Idea: define a list table, but the contents of the list table are allowed to be repeated, so you can use the contains method to query. If there is any, you will not add it, and if there is no, you will continue to add it!

The code is as follows (example):

public static void main(String[] args) {
        String[] strs = {"10001","10086","12347806666","45612378901","10001","12347806666"};
        LinkedList<String> data = addlist(strs);
        //Use the iterator to output all the elements in the list
        Iterator<String> integer = data.iterator();
        while (integer.hasNext()){
            String tex = integer.next();
            System.out.println(tex);
        }
        //Use enhanced for to output all elements in the list
        for (String string : data
        ) {
            System.out.println(string);
        }
    }
    /**
     * Add the elements in the array to the table without duplicate elements
     * @param strs String added to the table
     * @return Returns a table that does not contain duplicate elements
     */
    private static LinkedList<String> addlist(String[] strs) {
        LinkedList<String> list = new LinkedList<>();
        for(int i=0;i< strs.length;i++){
            if(list.contains(strs[i])){
                continue;
            }
            list.add(strs[i]);
        }
        return list;
    }

The operation screenshot is as follows:

3, Please randomly generate a two-color ball number

Example: two color ball rule: each betting number of two-color ball consists of 6 red ball numbers and 1 blue ball number. The red ball number is selected from 1-33; The blue ball number is selected from 1-16. (the same color number shall not be repeated)
Idea: if you think that the same color numbers are not repeated, the set will not contain repeated elements. Can you use HashSet to store random numbers.

The code is as follows (example):

public static void main(String[] args) {
        System.out.println("Randomly generate a two-color ball!");
        Random r = new Random();
        HashSet<Integer> set = new HashSet<>();//Used to store random numbers without duplicate data
        while(set.size()<6){
            int redBall = r.nextInt(33)+1;//Generate random numbers from 1 to 33
            set.add(redBall);
        }
        System.out.print("The red number ball is:");
        for (Integer data:set) {
            System.out.print(data +" ");//Output using enhanced for
        }
        int blueBall = r.nextInt(16)+1;//Generate random numbers from 1 to 16
        set.add(blueBall);
        System.out.println("The blue number ball is:"+blueBall);
    }

The operation screenshot is as follows:

4, Rank the scores of the following four students in descending order

Example: use the two interfaces of Comparable and Comparator to sort the grades of the following four students in descending order. If the grades are the same, sort them according to their age on the basis of grade sorting.
For example:
|Name (String) | age (Int) | score|
|Jia Baoyu | 14 | 88.5|
|Lin Daiyu | 13 | 90.5|
|Shi Xiangyun | 13 | 91.0|
|Xue Baochai | 15 | 91.0|

Idea:
1. Use the Comparable interface, rewrite CompareTo, and sort the grades in descending order. The grades are the same, and are sorted according to age;

The code is as follows (example):

public static void main(String[] args) {
        TreeSet<student> stu = new TreeSet<>();
        student stu1 = new student("Jia Baoyu",14,88.5);
        student stu2 = new student("Lin Daiyu",13,90.5);
        student stu3 = new student("Shi Xiangyun",13,91.0);
        student stu4 = new student("Xue Baochai",15,91.0);
        stu.add(stu1);
        stu.add(stu2);
        stu.add(stu3);
        stu.add(stu4);
        for (student data:stu) {
            System.out.println(data);
        }
    }
    /**
     * Student category, including name, age, grade
     * Rewrite complex and sort the grades in descending order. The grades are the same and sorted according to age
     */
    public static class student implements Comparable<student>{
        private String name;
        private int age;
        private Double grade;
        @Override
        public int compareTo(student o) {
            if(this.grade>o.grade){
                return -1;
            }else if(this.grade.equals(o.grade)){
               if(this.age>o.age){
                   return 1;
               }else{
                   return -1;
               }
            }
            return 1;
        }
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            student student = (student) o;
            return age == student.age && Objects.equals(name, student.name) && Objects.equals(grade, student.grade);
        }
        @Override
        public int hashCode() {
            return Objects.hash(name, age, grade);
        }
        public student(String name, int age, Double grade) {
            this.name = name;
            this.age = age;
            this.grade = grade;
        }
        public student() {
        }
        public String getName() {
            return name;
       }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public Double getGrade() {
            return grade;
        }
        public void setGrade(Double grade) {
            this.grade = grade;
        }
        @Override
        public String toString() {
            return "student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", grade=" + grade +
                    '}';
        }
    }

The operation screenshot is as follows:

2. Using the Comparator interface, first define a student class, rewrite the compare interface, and sort the grades in descending order. If the grades are the same, sort them according to age;

The code is as follows (example):

public static void main(String[] args) {
        TreeSet<Student> stu = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.getGrade()>o2.getGrade()){
                    return -1;
                }else if(o1.getGrade()== o2.getGrade()){
                    if(o1.getAge()> o2.getAge()){
                        return -1;
                    }else if(o1.getAge()< o2.getAge()){
                        return 1;
                    }else{
                        return 0;
                    }
                }else {
                    return 1;
                }
            }
        });
        Student st1 = new Student("Jia Baoyu",14,88.5);
        Student st2 = new Student("Lin Daiyu",13,90.5);
        Student st3 = new Student("Shi Xiangyun",13,91.0);
        Student st4 = new Student("Xue Baochai",15,91.0);
        stu.add(st1);
        stu.add(st2);
        stu.add(st3);
        stu.add(st4);
        for (Student data:stu
             ) {
            System.out.println(data);
        }
    }
Definition of student class
public class Student {
    private String name;
    private int age;
    private Double grade;
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name) && Objects.equals(grade, student.grade);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age, grade);
    }
    public Student(String name, int age, Double grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }
    public Student() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Double getGrade() {
        return grade;
    }
    public void setGrade(Double grade) {
        this.grade = grade;
    }
    @Override
    public String toString() {
        return "student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", grade=" + grade +
                '}';
    }

The operation screenshot is as follows:

summary

The above is the idea and code sharing of some test questions about data structure. This paper only briefly introduces the thinking of these test questions. The code is for reference only. If there is anything wrong, please exchange and correct it.

Keywords: Java IntelliJ IDEA data structure

Added by bolter on Fri, 04 Mar 2022 07:20:43 +0200