简体   繁体   English

Java链表问题

[英]Java linked list issue

I've been working on a linked list, but have hit a bit of a snag. 我一直在处理链表,但遇到了一些麻烦。 The list is supposed to be a representation of athlete objects containing their names and scores. 该列表应该是包含其名称和分数的运动员对象的表示。 The athlete class was supplied to me, and I am therefore not supposed to change it. 为我提供了运动员课程,因此我不应该更改它。 I've completed most of the competition class, but according to the rubric am now supposed to print the top 3 scores from the list. 我已经完成了大部分比赛课,但是根据专栏目,现在应该列出该榜单的前三名。 I've tried a couple different approaches, but have had no luck. 我尝试了几种不同的方法,但是没有运气。 Does anyone have any idea as to how I could accomplish this? 有谁对我如何做到这一点有任何想法吗? Below is the source code, the Competition and CompetitionDriver classes are ones of which I have developed. 下面是源代码,我开发了Competition和CompetitionDriver类。 By the way, this is for a university course. 顺便说一句,这是针对大学课程的。 Thanks to anyone with suggestions! 感谢任何有建议的人!

Athlete.java: Athlete.java:

public class Athlete implements Comparable {

  private String name;
  private int score;

  public Athlete (String n, int s) {
    name = n;
    score = s;
  }

  public int getScore() {
    return score;
  }

  public String toString() {
    return name;
  }

  public int compareTo(Object other) {
    return (score - ((Athlete)other).getScore());
  }
}

Competition.java: Competition.java:

public class Competition {

  private Athlete current;
  private Competition next;

  public Competition() {
    current = null;
    next = null;
  }

  public Competition(Athlete currentIn, Competition nextIn) {
    current = currentIn;
    next = nextIn;
  }

  public void addToEnd(Athlete input) {
    if (current != null) {
      Competition temp = this;
      while (temp.next != null) {
        temp = temp.next;
      }
      temp.next = new Competition(input, null);
    }
    else {
      current = input;
    }
  }

  public void print() {
    Competition temp = this;
    while(temp != null) {
      System.out.println("\nAthlete name: " 
                         + temp.current.toString() 
                         + "\nAthlete score: "
                         + temp.current.getScore());
      temp = temp.next;
    }
  }     
}

CompetitionDriver.java: CompetitionDriver.java:

public class CompetitionDriver {

  public static void main(String[] args) {

    Competition competition = new Competition();

    competition.addToEnd(new Athlete("Jane", 7));
    competition.addToEnd(new Athlete("Mark", 9));
    competition.addToEnd(new Athlete("Mary", 6));
    competition.addToEnd(new Athlete("Eve", 2));
    competition.addToEnd(new Athlete("Dan", 15));
    competition.addToEnd(new Athlete("Adam", 4));
    competition.addToEnd(new Athlete("Bob", 3));
    competition.addToEnd(new Athlete("Kathy", 8));
    competition.addToEnd(new Athlete("John", 5));
    competition.addToEnd(new Athlete("Rob", 1));

    competition.print();

    competition.printTop();

  }
}

You have two options: 您有两种选择:

1) Go through each node and determine the top 3 scores. 1)遍历每个节点并确定前3个得分。 (I would not recommend this as it requires having to keep track of the top three scores as you go through each and every node) (我不建议您这样做,因为它要求您在遍历每个节点时都必须跟踪前三名得分)

2) Always have your linked list be sorted in descending order. 2)始终将您的链表按降序排列。 This way when you need to find the top three you start from the first node, and go to the next two nodes. 这样,当您需要查找前三个节点时,您将从第一个节点开始,然后转到下两个节点。 This also means that upon inserting/deleting you need to sort your list. 这也意味着插入/删除后,您需要对列表进行排序。 I suggest looking into the Heap datastructure . 我建议研究一下Heap数据结构

Add this to your class Competition: 将此添加到您的班级竞赛中:

public void threeStrongest() {
    Competition temp = this;
    int best = this.current.getScore();
    int best2 = 0;
    int best3 = 0;
    int i = 0;
    while(i < 3) {

        if(temp.current.getScore() > best){
            best3 = best2;
            best2 = best;
            best = temp.current.getScore();
        }
        else if(temp.current.getScore() > best2){
            best3 = best2;
            best2 = temp.current.getScore();
        }
        else {
            best3 = temp.current.getScore();
        }

        i++;
        temp = temp.next;
    }

    while(temp != null) {

        if(temp.current.getScore() > best){
            best3 = best2;
            best2 = best;
            best = temp.current.getScore();
        }
        else if(temp.current.getScore() > best2){
            best3 = best2;
            best2 = temp.current.getScore();
        }
        else if(temp.current.getScore() > best3){
            best3 = temp.current.getScore();
        }
        temp = temp.next;
    }

    System.out.println(best + " " + best2 + " " + best3);
}

This works for the example you gave. 这适用于您给出的示例。 Hopefully it works for all examples too. 希望它也适用于所有示例。

EDIT: Don't forget to add this method to your main like this: competition.threeStrongest(); 编辑:不要忘了像这样将这种方法添加到您的主体中: Competition.threeStrongest();

use following code for: 使用以下代码:

Compitition.java: Compitition.java:

public class Competition {

      private Athlete current;
      private Competition next;

      public Competition() {
        current = null;
        next = null;
      }

      public Competition(Athlete currentIn, Competition nextIn) {
        current = currentIn;
        next = nextIn;
      }

      public void addToEnd(Athlete input) {
        if (current != null) {
          Competition temp = this;
          while (temp.next != null) {
            temp = temp.next;
          }
          temp.next = new Competition(input, null);
        }
        else {
          current = input;
        }
      }


     Map<Integer,String> map=new HashMap<Integer,String>(); 
     List<Integer> list=new ArrayList<Integer>();
      public void print()
      {
        Competition temp = this;
        while(temp != null) 
        {
          System.out.println("\nAthlete name: " 
                             + temp.current.toString() 
                             + "\nAthlete score: "
                             + temp.current.getScore());
          map.put(temp.current.getScore(),temp.current.toString());
          list.add(temp.current.getScore());
          temp = temp.next;
        }

      }   

        public void printTop()      
        {



            Collections.sort(list);         

            int a[]={list.get(list.size()-1),list.get(list.size()-2),list.get(list.size()-3)};

            for(int i=0;i<a.length;i++)
            {


            for (Map.Entry<Integer,String> entry : map.entrySet()) {

                if(entry.getKey().equals(a[i]))
                {
                    System.out.println(entry.getKey()+"  "+entry.getValue());
                }


            }

            }

        }

    }

and CompetitionDriver.java 和CompetitionDriver.java

public class CompetitionDriver {

      public static void main(String[] args) {

        Competition competition = new Competition();

        competition.addToEnd(new Athlete("Jane", 7));
        competition.addToEnd(new Athlete("Mark", 9));
        competition.addToEnd(new Athlete("Mary", 6));
        competition.addToEnd(new Athlete("Eve", 2));
        competition.addToEnd(new Athlete("Dan", 15));
        competition.addToEnd(new Athlete("Adam", 4));
        competition.addToEnd(new Athlete("Bob", 3));
        competition.addToEnd(new Athlete("Kathy", 8));
        competition.addToEnd(new Athlete("John", 5));
        competition.addToEnd(new Athlete("Rob", 1));

        competition.print();

       competition.printTop();

      }
    }

and run it. 并运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM