实现一个链表,最多存储10个名字,按先进先出的顺序排列。然后实现两种方法,其中一种按姓氏字母顺序对其进行排序。这就是我遇到麻烦的地方。这是我尝试过的:
递归。该方法调用两个节点,比较它们,如果需要则交换,然后调用自身。不适用于奇数个名称,并且往往是完整的错误。
Collection ,但我对它了解不够,无法有效使用它。
排序算法(例如冒泡排序):我可以遍历列表,但很难交换节点。
我的问题是:最简单的方法是什么?
public class List
{
public class Link
{
public String firstName;
public String middleName;
public String lastName;
public Link next = null;
Link(String f, String m, String l)
{
firstName = f;
middleName = m;
lastName = l;
}
}
private Link first_;
private Link last_;
List()
{
first_ = null;
last_ = null;
}
public boolean isEmpty()
{
return first_ == null;
}
public void insertFront(String f, String m, String l)
{
Link name = new Link(f, m, l);
if (first_ == null)
{
first_ = name;
last_ = name;
}
else
{
last_.next = name;
last_ = last_.next;
}
}
public String removeFront()
{
String f = first_.firstName;
String m = first_.middleName;
String l = first_.lastName;
first_ = first_.next;
return f + " " + m + " " + l;
}
public String findMiddle(String f, String l)
{
Link current = first_;
while (current != null && current.firstName.compareTo(f) != 0 && current.lastName.compareTo(l) != 0)
{
current = current.next;
}
if (current == null)
{
return "Not in list";
}
return "That person's middle name is " + current.middleName;
}
}
public class NamesOfFriends
{
public static void main(String[] args)
{
List listOfnames = new List();
Scanner in = new Scanner(System.in);
for(int i = 0; i < 3; i++)
{
if(i == 0)
{
System.out.println("Please enter the first, middle and last name?");
listOfnames.insertFront(in.next(), in.next(),in.next());
}
else
{
System.out.println("Please enter the next first, middle and last name");
listOfnames.insertFront(in.next(), in.next(),in.next());
}
}
System.out.println("To find the middle name, please enter the first and last name of the person.");
System.out.println(listOfnames.findMiddle(in.next(),in.next()));
}
}
编辑
经过一番研究后,我弄清楚了如何对其进行排序。为此,我尝试实现一个删除方法,该方法可以删除列表中任何位置的节点。虽然它确实可以编译,但当我运行该程序时它不会执行任何操作。
public Link remove(String lastName)
{
Link current_ = first_;
Link prior_ = null;
Link temp_ = null;
while (current_ != null && current_.lastName.compareTo(lastName) != 0)
{
prior_ = current_;
current_ = current_.next;
}
if (current_ != null)
{
if (current_ == last_)
{
temp_ = last_;
last_ = prior_;
}
else if (prior_ == null)
{
temp_ = first_;
first_ = first_.next;
}
}
else
{
temp_ = current_;
prior_.next = current_.next;
}
return temp_;
}
最佳答案
2: Collection 是最简单的,但是作业里好像不允许使用
3:冒泡排序很简单,但却是最糟糕的已知排序算法,但对于你的家庭作业来说,它可能还可以
1:这与冒泡排序相同,但最好不使用递归来完成
在冒泡排序中,您一次又一次地循环遍历元素,直到不再需要交换为止,然后就准备好了。
关于java - 使用Java中的方法对单链表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13868802/