【问题标题】:Sorting a Linked List in alphabetical order按字母顺序对链表进行排序
【发布时间】:2019-05-14 21:36:44
【问题描述】:

我有一个任务,我必须创建一个链接列表,其中包含一个人姓名和他们进入一个大院的车牌号码。但我需要使用车牌号(例如:ABS1234)按字母顺序对列表进行排序。我一直在对排序进行一些研究,例如合并排序或使用 collection.sort,但我无法理解它。如果我能稍微推动一下如何做到这一点,那就太棒了。提前致谢。

public class Node {
//data fields
public String regPlate; // Registration Plate
public String firstName;
public String lastName;

//refrence link
public Node link;

//default constructor
public Node()
{
    regPlate = "";
    firstName = "";
    lastName = "";
}//end of constructor.

}//end of node class

这是我创建的 Node 类。

public class LinkedList {

Node head;
Node tail;
Node current;
int listLength;
Scanner input = new Scanner(System.in);

//default constructor
public LinkedList () 
{
    head = null;
    listLength = 0;
}

//inserting new node in the beginning of the list
public void insertFirst(String fN, String lN, String rP)
{

    Node newNode = new Node();
    newNode.firstName = fN;
    newNode.lastName = lN;
    newNode.regPlate = rP;

    //make newNode point to the first node in the life
    newNode.link = head;

    //makes head point to the new first node
    head = newNode;

    if(head == null)
        tail = newNode;

    ++listLength;
}//end of insertFirst


public void displayDataLog()
{
    Node current;

    current = head;

    while(current != null)
    {
        System.out.print("\n FullName: " + current.firstName + " " + current.lastName +
                        "\n Registration Plate Number: " + current.regPlate);

        current = current.link;
    }

}//end of display vehicles

public void totalVehicles()
{
    System.out.print("\n Total Vehicle on the campus: " + listLength);
}//end of total vehicles


}//end of linked list

【问题讨论】:

  • 什么是“BlinkList”?您只是说“链接列表”吗?
  • 是的链表
  • 必须实现排序算法吗?或者你可以使用 Collection.sort 吗?
  • 我可以使用 collection.sort 但不知道怎么用

标签: java sorting singly-linked-list


【解决方案1】:

使用 Collection.sort() 这应该很容易。

首先,您需要创建自己的Comparator,因为默认的不起作用(您想按特定字段订购,即车牌)。

class NodeComparator implements Comparator<Node> {
    @Override
    public int compare(Node n1, Node n2) {
        return n1.regPlate.compareTo(n2.regPlate);
    }
}

现在你有了你的比较器,就用它吧,这是我用的一个例子(创建了一个 ArrayList 并在那里引入了列表的每个元素):

private static LinkedList sortList(LinkedList list) {
    // I use an ArrayList so I can just use Collections.sort
    LinkedList sortedList = new LinkedList();
    Node current = list.head;
    ArrayList<Node> array = new ArrayList<Node>();

    while (current != null) {
        array.add(current);
        current = current.link;
    }
    array.sort(new NodeComparator());

    for (int i = array.size()-1; i >= 0; i--) {
        sortedList.insertFirst(array.get(i));
    }

    return sortedList;
}

我做了一些更改,很可能很容易适应您自己的程序。您可以在此处查看完整的工作程序:https://code.sololearn.com/cgzN5sQOI8uW



完整的代码,以防万一链接停止工作:

import java.util.*; 
import java.lang.*; 
import java.io.*;

class Playground {
    public static void main(String[ ] args) {
        LinkedList list = new LinkedList();
        list.insertFirst("Robert", "Rodriguez", "RB123");
        list.insertFirst("Andrew", "Andrews", "AB123");
        list.insertFirst("Thomas", "Thomson", "TB123");

        System.out.println(list); // Prints unordered list, opposite order as they were introduced, since they were introduced from the beggining of the list.

        LinkedList sorted = sortList(list);
        System.out.println("\n"+sorted);
    }

    private static LinkedList sortList(LinkedList list) {
        // I use an ArrayList so I can just use Collections.sort
        LinkedList sortedList = new LinkedList();
        Node current = list.head;
        ArrayList<Node> array = new ArrayList<Node>();

        while (current != null) {
            array.add(current);
            current = current.link;
        }
        System.out.println("\nTemp Array:");
        System.out.println(array);

        array.sort(new NodeComparator());

        System.out.println("\nTemp Array (now sorted):");
        System.out.println(array);

        for (int i = array.size()-1; i >= 0; i--) {
            sortedList.insertFirst(array.get(i));
        }

        return sortedList;
    }
}

class NodeComparator implements Comparator<Node> {
    @Override
    public int compare(Node n1, Node n2) {
        return n1.regPlate.compareTo(n2.regPlate);
    }
}

class Node {
    //data fields
    public String regPlate; // Registration Plate
    public String firstName;
    public String lastName;

    //refrence link
    public Node link;

    //default constructor
    public Node()
    {
        regPlate = "";
        firstName = "";
        lastName = "";
    }//end of constructor.

    public String toString() {
        return this.regPlate;
    }



}//end of node class

class LinkedList {

    Node head;
    Node tail;
    Node current;
    int listLength;

    //default constructor
    public LinkedList () 
    {
        head = null;
        listLength = 0;
    }

    //inserting new node in the beginning of the list
    public void insertFirst(String fN, String lN, String rP)
    {

        Node newNode = new Node();
        newNode.firstName = fN;
        newNode.lastName = lN;
        newNode.regPlate = rP;

        insertFirst(newNode);
    }//end of insertFirst

    public void insertFirst(Node newNode) {
        //make newNode point to the first node in the life
        newNode.link = head;

        //makes head point to the new first node
        head = newNode;

        if(head.link == null)
            tail = newNode;

        ++listLength;
    }

    public void displayDataLog()
    {
        Node current;

        current = head;

        while(current != null)
        {
            System.out.print("\n FullName: " + current.firstName + " " + current.lastName +
                            "\n Registration Plate Number: " + current.regPlate);

            current = current.link;
        }

    }//end of display vehicles

    public void totalVehicles()
    {
        System.out.print("\n Total Vehicle on the campus: " + listLength);
    }//end of total vehicles

    public String toString() {
        String str = "List:\nhead -> [ ";
        Node current = head;

        while (current != null) {
            str = str + current + (current == tail ? " ] <- tail" : ", ");
            current = current.link;
        }

        return str;
    }

}//end of linked list

【讨论】:

  • 我有点理解你是怎么做到的。我以前从未见过的代码中的一些东西让我有点困惑,但我想我明白了。如果你不介意,问几个问题。 @Override 的目的是什么意味着如果 insertFirst 函数需要三个字符串变量,array.get(i) 是如何工作的?
  • 在提问之前先做一些研究。 @Override 用于覆盖现有函数。因此,您替换了该类中已经存在的函数。
  • 他声明了 2 个名为 insertFirst() 的函数,一个函数接受 3 个参数,另一个只接受 1 个参数。因此,如果您使用一个参数调用 insertFirst(),它将调用接受一个参数的函数,如果您调用它与三个它将调用带有三个参数的函数。
  • 我认为 dquijada 创建了一个名为 LinkedList 的类,它已经存在于 java.util 中,这令人困惑。* 不同的名称不是更好吗?
  • @JosiahFrancis @Override 注释使它覆盖它扩展/实现的类/接口的方法。因此,当您执行“.compare()”时,它会调用它而不是超类之一。我还重载了方法“insertFirst”,这意味着:根据参数,它将调用一个或另一个
猜你喜欢
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 2011-08-29
  • 2021-08-10
  • 2013-05-02
  • 2014-02-08
  • 1970-01-01
相关资源
最近更新 更多