单链表的应用举例

来源:互联网 发布:赵孟頫字画鉴定知乎 编辑:程序博客网 时间:2024/05/17 07:11

要求:设计一个成员函数,要求在单链表中插入一个数据元素x,并要求插入后单链表中的数据元素从小到大有序排列。

思路:很简单,就是拿x从链表第一个元素一个个比较下去,找到合适的位置插入。

注意:我们是拿Integer类的x和Node类(结点类)的data数据进行比较分出大小,而不是判断是否相等。Object中的equals只是比较两个对象是否相等。所以我们要借助java.util包里的比较器Comparator(接口)来实现大小比较。

我们在此不再重复定义线性表方法类(Link)、结点类(Node)和单链表类(LinList)上文有代码。

直接看实现的比较器代码:

import java.util.*;//定义比较器class MyComparator implements Comparator{public int compare(Object o1,Object o2){if((o1 instanceof Integer) && (o2 instanceof Integer)){Integer co1 = (Integer)o1;Integer co2 = (Integer)o2;int i1 = co1.intValue();int i2 = co2.intValue();if(i1<=i2) return 1;else return -1;}else{return 0;}}public boolean equals(Object obj){//该方法没用到,但必须实现。return false;}}

我们把按序插入操作单独写成一个方法并在主函数中调用解决问题:

public class LinListDemo {public static void orderInsert(LinList myList,Object x,Comparator mc){ //传入链表,需要插入的数和比较器Node curr,pre;curr = myList.head.next;//设置从头开始遍历pre = myList.head;while(curr!=null && (mc.compare(curr.data,x)==1)){pre = curr;curr = curr.next;}Node temp = new Node((Integer)x,pre.next);//找到位置后封装新的结点并插入到相应位置pre.next = temp;myList.size++;}public static void main(String[] args) {MyComparator mc = new MyComparator();LinList myList = new LinList();int []s = {1,3,9,11,8,6,22,16,15,10};int n = 10;try{for(int i=0;i<n;i++){//相当于把元素插入到空表中并排好序orderInsert(myList,new Integer(s[i]),mc);}for(int i=0;i<myList.size;i++){System.out.print(myList.getData(i)+" ");}System.out.println();orderInsert(myList,new Integer(13),mc);//在链表中插入元素13for(int i=0;i<myList.size;i++){System.out.print(myList.getData(i)+" ");}}catch(Exception e){System.out.println(e.getMessage());}}}/*1 3 6 8 9 10 11 15 16 22 1 3 6 8 9 10 11 13 15 16 22  */

变形:对链表中的元素进行就地排序。就地排序是指在排序过程中利用原有的结点,不额外增加新结点。

思路:把原链表从头结点砍掉,也就是原链表置空,再把去掉头结点的链表数据元素逐个插入新单链表,这样就和上题一样了。

看代码(不做过多注释了):

public class LinListDemo {public static void linListSort(LinList L,Comparator mc){Node curr;curr = L.head.next;L.head.next = null;L.size = 0;while(curr!=null){orderInsert(L,curr.data,mc);curr = curr.next;}}public static void orderInsert(LinList myList,Object x,Comparator mc){Node curr,pre;curr = myList.head.next;pre = myList.head;while(curr!=null && (mc.compare(curr.data,x)==1)){pre = curr;curr = curr.next;}Node temp = new Node((Integer)x,pre.next);pre.next = temp;myList.size++;}public static void main(String[] args) {MyComparator mc = new MyComparator();LinList myList = new LinList();int []s = {1,3,9,11,8,6,22,16,15,10};int n = 10;try{for(int i=0;i<n;i++){//和上一串代码区别的地方,插入的时候按照输入顺序,上题是边插入边排序//orderInsert(myList,new Integer(s[i]),mc);myList.insert(i, new Integer(s[i]));}System.out.print("排序前数据元素:\n");for(int i=0;i<myList.size;i++){System.out.print(myList.getData(i)+" ");}linListSort(myList,mc);System.out.print("\n排序后数据元素:\n");for(int i=0;i<myList.size;i++){System.out.print(myList.getData(i)+" ");}}catch(Exception e){System.out.println(e.getMessage());}}}/*排序前数据元素:1 3 9 11 8 6 22 16 15 10 排序后数据元素:1 3 6 8 9 10 11 15 16 22  */

over!欢迎指正。

0 0