按字母顺序排序链表

问题描述

我想对节点选择的字符串变量进行排序。这是明天的作业。

    public void sortSongName() {
        
        DefaultSongs sortedList = new DefaultSongs();
        
        int temp= Integer.MAX_VALUE;
        Song curr=root;
        Song hold = null;
        
        while(root.nextSong != null) {
            
            if(curr.getSongName().charat(0)<hold.getSongName().charat(0)) {
                hold=curr;
                curr=root.nextSong;
            }else {
                curr=root.nextSong;
            }
            
            sortedList.createSong(root.nextSong.getSongName(),root.nextSong.getBandName(),root.nextSong.getDuration());
            deleteSong(root.nextSong.getSongName());
            sortSongName();
        }
    }

解决方法

假设你的歌曲类看起来像这样

public class Song {
   private String name;

   public String name() {
       return name;
   }

   public void setName(final String name) {
       this.name = name;
   }
}

而 DefaultSongs 类只是一个带有歌曲列表的存储库

public class DefaultSongs {

   private final List<Song> songList;

   public DefaultSongs() {
       this.songList = new ArrayList<>();
   }

   public List<Song> songList() {
       return songList;
   }
}

最简单的方法是使用java流

public void sortSongsByName(){
    songList.stream().sorted(Comparator.comparing(Song::name));
}