实现插入排序,将列表传递给其他类?

时间:2012-04-18 07:05:34

标签: java list linked-list insertion

我昨天发布了一个版本的代码,但我认为它可以处理一些改进或其他什么。事情再次陷入困境。你可以看到我试图对链表进行排序并将其写回文本文件。第一个问题是,什么以及如何传入Insertion类?第二个问题是如何实现插入排序ALPHABETICALLY?我已经看到了许多使用整数和数组插入的例子,但我似乎仍然遇到了麻烦。到目前为止,这是我的进展。

编辑1:忘记了。

编辑2:如何实现Comparable并使用我的方法按字母排序(CompareToIgnoreCase)?

主:

import java.io.* ;
import java.util.Scanner ;

public class Sort 
{
    public static void main(String[] args) throws Exception 
    {
        File outputFile ;
        Scanner kb = new Scanner (System.in) ; 
        LinkedList list = new LinkedList() ;
        String command ;
        Insertion insertion = new Insertion() ;

        // Create the new text file. If exists, it will continue to the next commands
        do
        {
            outputFile = new File("db.txt") ;

                if(!outputFile.exists())
                {
                    outputFile.createNewFile ();                    
                    System.out.println("The file was created as db.txt");
                    System.out.println("");
                }

        }while (!outputFile.exists()) ;

        // Define which file to stream in from          
        FileInputStream fileIn = new FileInputStream("db.txt") ;
        DataInputStream input = new DataInputStream (fileIn) ;
        BufferedReader br = new BufferedReader (new InputStreamReader (input)) ;
        String line ;

        try
        {               
            // Read each line of the file               
            while ((line = br.readLine()) != null)
            {
                list.add(line) ;
            }       
            input.close() ;
        }catch (Exception e){
            System.err.println("Error. Could not read the file") ;
        }

        //System.out.println (list.toString()) ;

        //Welcome message
        System.out.println("Welcome. \nPlease use the following commands [-i for Insertion Sort, -s for Selection Sort, -m for Merge sort, Exit to terminate]: " );
        System. out.println ("") ;          
        command = kb.next() ;

        do
        {
            if (command.equalsIgnoreCase("-i"))
            {
                insertion.Sort(list, list.size()) ;

                //try
                //{
                    //the "true" argument sets the FileWriter to append mode so that is does not overwrite the first line
                //  BufferedWriter out = new BufferedWriter(new FileWriter("db.txt", true));
                    //out.write(textContent) ;
                    //out.newLine() ;
                    //out.close() ;
                //}catch(IOException e)
                //{
                //  System.out.println("Could not write to file") ;
                //  System.exit(0) ;
                //}

                //System.out.println ("Enter command:") ;
                //command = kb.next() ;

            }

            else if (command.equalsIgnoreCase("-s"))
            {

            }
            else if (command.equalsIgnoreCase("-m"))
            {

            }
            else if (command.equalsIgnoreCase("Exit"))
            {
                System.exit(0) ;
            }
            else 
            {
                System.out.println("Unknown command. Please use -i, -s, -m or EXIT") ;
                command = kb.next() ;
            }
        }while (!command.equalsIgnoreCase("Exit")) ;

    }
}

链表:

    import java.lang.* ;

public class LinkedList
{
    //reference to the head node
    public Node head ;
    public int listCount ;

    //LinkedList Constructor
    public LinkedList ()
    {
        //empty list
        head = new Node (null) ;
        listCount = 0 ;
    }

    //add element to the end of the list
    public void add(String data)
    {
        Node temp = new Node (data) ;
        Node current = head ;

        //go to the end of the list
        while (current.getNext() != null)
        {
            current = current.getNext() ;
        }

        // last node\s next reference is set to the last node
        current.setNext(temp) ;
        //increment the number of elements
        listCount++ ; 
    }

    //return the size of the list
    public int size()
    {
        return listCount ;
    }

    public String toString()
    {
        Node current = head.getNext() ;
        String output = " " ;
        while (current != null)
        {
            output += "[" + current.getData().toString() + "]" ;
            current = current.getNext() ;
        }
        return output ;
    }


}

插入:

public class Insertion 
{
    public static void Sort (LinkedList listIn, int size)
    {
        int temp, i, j ;
        for (j=1;j<size;j++)
        {
            while(listIn.head)
        }
    }
}

节点类:

    public class Node 
    {
        //reference to the next node or null if not any
        Node next ;
        //the entries
        String data ;

        //Node Constructor
        public Node (String dataIn)
        {
            next = null ;
            data = dataIn ;
        }

        //Node constructor in case of the need to point to a certain node
        public Node (String dataIn, Node nextIn)
        {
            next = nextIn;
            data = dataIn ;
        }

        public String getData ()
        {
            return data ;
        }

        public void setData (String dataIn)
        {
            data = dataIn ;
        }

        public Node getNext ()
        {
            return next ;
        }

        public void setNext (Node nextIn)
        {
            next = nextIn ;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

  

传入插入类的内容和方式?

你的意思是方法?你应该传递(至少)完整的LinkedList(而不仅仅是头部Node)。

  

第二个问题是如何实现插入排序ALPHABETICALLY?

要么接受类型实现Comparable的元素列表,要么采用单独的Comparator参数,并使用它来比较元素。然后,您可以传递StringComparator以获取String的列表,IntComparator的{​​{1}}等等。您只需要实现所需的比较器,通常是因此,你可以重复使用你想要的任何类型的排序算法。

第一种方法更简单,它适用于Integer直接开箱即用(因为String已经实现了String)。但请注意,它仅限于对象类型 - 对于基本类型(如Comparable),您需要第二种方法。然后,您不能拥有存储基本类型元素的泛型集合。

您可以在Collections中看到两种通用int方法的示例:

sort

如果你想保留public static <T extends Comparable<? super T>> void sort(List<T> list); public static <T> void sort(List<T> list, Comparator<? super T> c) 非通用,你可以删除(大部分)通用绒毛:

LinkedList