简体   繁体   English

链表插入方法

[英]Linked List insert method

In the process of writing a class that demonstrates a linked list and I'm not getting the results I need. 在编写演示链接列表的类的过程中,我没有得到所需的结果。 I have written a class that contains an inner node class as well as an insert method that adds a name and score to the list, limits the list to ten by removing the person with the lowest score. 我编写了一个包含内部节点类的类,以及一个将名称和分数添加到列表中的插入方法,通过删除分数最低的人将列表限制为十个。 I have also created a test GUI program. 我还创建了一个测试GUI程序。 When ran and type the insert command the list displays the name of my class (GamerList) followed by "@" and numbers rather than the desire name and score. 运行并键入插入命令后,列表将显示我班级的名称(GamerList),后跟“ @”和数字,而不是所需的名称和分数。 I suspect my problem to be somewhere in my insert method. 我怀疑我的问题出在我的插入方法中。 Any feedback would be much appreciated. 任何反馈将不胜感激。

Linked List Class 链表类

    class GameList
   {
  //node class

  private class Node
  {
    String name;
    int score;
    Node next;

    //Node constructor
    Node(String namVal, int scrVal, Node n)
    {
      name = namVal;
      score = scrVal;
      next = n;
    }

    //Constructor
    Node(String namVal, int scrVal)
    {
      this(namVal, scrVal, null);
    }
  }

  private Node first; //head
  private Node last;  //last element in list

  //Constructor

  public GameList()
  {
    first = null;
    last = null;
  }

  //isEmpty method: checks if param first is empty
  public boolean isEmpty()
  {
    return first == null;
  }

  public int size()
  {
    int count = 0;
    Node p = first;

    while(p != null)
    {
      count++;
      p = p.next;
    }
    return count;
  }

 //Override toString
public String toString()
{
  StringBuilder strBuilder = new StringBuilder();

  // Use p to walk down the linked list
  Node p = first;
  while (p != null)
  {
     strBuilder.append(p.name); 
     p = p.next;
  }      
  return strBuilder.toString(); 
}



  public void insert(String name, int score)
  {
    Node node = new Node(name, score);
    final int MAX_LIST_LEN = 10;

    if(isEmpty())
    {
      first = node;
      first.next = last;
    }

    else if(first.score <= node.score)
    {
      node.next = first;
      first = node;
    }

    else
    {
      Node frontNode = first;
      while(frontNode.score > node.score && frontNode.next != null) 
      {
                frontNode = frontNode.next;
      }
      node.next = frontNode.next;
      frontNode.next = node;
    }

    if(size() > MAX_LIST_LEN)
    {
      Node player = first;
      for(int i = 0; i < 9; i++)
      {
        player = player.next;
      }
      player.next = null;
    }
  }
}

Test Program 测试程序

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/**
   This class is used to demonstrate
   the operations in the GameList class.
*/

public class GameListGui extends JFrame
{    
    private  GameList topGamers;
    private JTextArea  listView;
    private JTextField cmdTextField;

    public GameListGui()
    {
       topGamers = new GameList(); 
       listView = new JTextArea();
       cmdTextField = new JTextField();

       // Create a panel and label for result field
       JPanel resultPanel = new JPanel(new GridLayout(1,2));
       resultPanel.add(new JLabel("Command Result"));
       add(resultPanel, BorderLayout.NORTH);

       // Put the textArea in the center of the frame
       add(listView);
       listView.setEditable(false);
       listView.setBackground(Color.WHITE);

       // Create a panel and label for the command text field
       JPanel cmdPanel = new JPanel(new GridLayout(1,2));
       cmdPanel.add(new JLabel("Command:"));
       cmdPanel.add(cmdTextField);
       add(cmdPanel, BorderLayout.SOUTH);  
       cmdTextField.addActionListener(new CmdTextListener());

       // Set up the frame
       setTitle("Linked List Demo");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       pack();
       setVisible(true);       
    }

        private class CmdTextListener
            implements ActionListener
    {            
        public void actionPerformed(ActionEvent evt)
        {
            String cmdText = cmdTextField.getText();
            Scanner sc = new Scanner(cmdText);
            String cmd = sc.next();
            if (cmd.equals("insert")){ 
                if (sc.hasNextInt())
                {
                    // add index element
                    int score = sc.nextInt();
                    String name = sc.next();
                    topGamers.insert(name, score);                
                }
                listView.setText(topGamers.toString());
                pack();
                return;
            }
        }
        }
            public static void main(String [ ] args)
    {
        new GameListGui();
    }    
}

I figured you had a call like this somewhere: 我发现您在某处打过这样的电话:

topGamers.toString()

toString , unless overridden, will print out the object's type and hash code. 除非被重写,否则toString将打印出对象的类型和哈希码。 Both of which are completely useless to those of us not concerned with the object's type and hash code as a printable representation. 对于我们中那些不关心对象类型和哈希码作为可打印表示形式的人来说,这两种方式都是完全没有用的。

What you want to do is implement a sane String representation of your GameList instead. 您要做的是改为实现GameList的合理的String表示。

@Override
public String toString() {
    // code
}

Well...there's a slight caveat - the GameList only holds Node s, so you have to pull information out of each node too. 嗯...有一点警告GameList仅包含Node ,因此您也必须从每个节点中提取信息。 That means, for Node , you're overriding toString() too. 这意味着,对于Node ,您也将覆盖toString()

I leave this portion as an exercise to the reader (the trawling of the list), but you would do well to gather the information of each node in a StringBuilder , then return its toString() value. 我将这一部分留给读者作为练习(列表的拖曳),但是您最好在StringBuilder收集每个节点的信息,然后返回其toString()值。

不,问题(在这种特定情况下,我没有检查您的列表是否确实应做的事情)是您尚未为链接列表类定义toString方法,因此它使用在中定义的默认toString object ,它打印类名称和内存位置。

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

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