首页 > 代码库 > 链表排序,查找,洗牌,旋转
链表排序,查找,洗牌,旋转
链表的排序和查找可以使用Collections类
排序,public static sort(List<E> list1)不实现Comparable的结点不能用
查找,int binarySearch(List<E> list2,T Key,CompareTo<T>)
都是第一个放链表对象,第二个放结点
结点要实现接口Comparable接口的compareTo方法作为比较标准,后面的参数可以写null
(比如Sring内部已经实现了compareTo方法,就是按照字典顺序排)
测试代码
package cgfg; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; public class Test{ public static void main(String args[]){ LinkedList<Student> list1=new LinkedList<Student>(); list1.add(new Student("huang",4)); list1.add(new Student("yu",2)); list1.add(new Student("cheng",5)); Iterator<Student> iterator1=list1.iterator(); for(;iterator1.hasNext();){ Student student=iterator1.next(); System.out.println(student.getHeight()); } Collections.sort(list1); iterator1=list1.iterator(); for(;iterator1.hasNext();){ Student student=iterator1.next(); System.out.println(student.getHeight()); } Student test=new Student("dd",5); int a=Collections.binarySearch(list1, test, null); Student b=list1.get(a); System.out.println(b.getName()); } } class Student implements Comparable{ private String name; private int height; Student(String a,int b){ name=a; height=b; } int getHeight(){ return height; } String getName(){ return name; } public int compareTo(Object b){ Student b2=(Student)b; return height-b2.height; } }
洗牌
public static void shuffle(List<E> list1)
旋转
public static void rotate(List<E> list1,int distance)//正数右转,负数左转
调转
public static void reverse(List<E> list1)
测试代码
package cgfg; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; public class Test{ public static void main(String args[]){ LinkedList<Student> list1=new LinkedList<Student>(); list1.add(new Student("huang",4)); list1.add(new Student("yu",2)); list1.add(new Student("cheng",5)); Iterator<Student> iterator1=list1.iterator(); for(;iterator1.hasNext();){ Student student=iterator1.next(); System.out.print(student.getHeight()); } System.out.println(""); Collections.shuffle(list1);//打乱 iterator1=list1.iterator(); for(;iterator1.hasNext();){ Student student=iterator1.next(); System.out.print(student.getHeight()); } System.out.println(""); Collections.rotate(list1,2);//右旋两次 iterator1=list1.iterator(); for(;iterator1.hasNext();){ Student student=iterator1.next(); System.out.print(student.getHeight()); } System.out.println(""); Collections.reverse(list1);//调转 iterator1=list1.iterator(); for(;iterator1.hasNext();){ Student student=iterator1.next(); System.out.print(student.getHeight()); } } } class Student implements Comparable{ private String name; private int height; Student(String a,int b){ name=a; height=b; } int getHeight(){ return height; } String getName(){ return name; } public int compareTo(Object b){ Student b2=(Student)b; return height-b2.height; } }
链表排序,查找,洗牌,旋转
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。