数据结构——把数据项按顺序插入到链表中(java实现)

来源:互联网 发布:网络女主播大尺度直播 编辑:程序博客网 时间:2024/05/18 16:14

      今天要记录的是有序链表,前几篇讲到的链表都是无序的,说他无序就是指没有什么规律的、乱序的,将这类链表输出后会发现,其输出顺序与操作链表时的输入顺序有很大关系——要么与输入顺序顺序相同要么与输入顺序相反,具体取决于所定义的插入函数是从链表头部还是从尾部插入;实际场景下可能有序链表使用的较多,要想实现这样一个链表:创建该链表后插入的元素都能按顺序排序,则必须在定义有序链表时在插入函数定义好插入规则(decreasing or increasing),这样在插入若干个数据项后,输出该链表的数据项会发现他们是有序排序的。

      在实现有序链表的插入规则时,按照自己的逻辑去实现总是达不到真实效果,可谓险象环生:死循环(用Eclipse单步调试显示无法找到某文件)、nullPointerException、只输出一个数据项、输出时少一个数据项、只输出最后插入的两个数据项,凡此足足,不一而足,按照书上的去做完全没有问题,可当碰到我怎么才能想到呢,不管他了,先记录下再说,代码如下:

class Link{public int iData;public double dData;public Link next;//-------------------------------------public Link(int iData, double dData){this.iData = iData;this.dData = dData;}//-------------------------------------public void displayLink(){System.out.print("{" + iData + ", " + dData + "}");}}class LinkList{private Link first;//--------------------public LinkList(){first = null;}//--------------------public boolean isEmpty(){return (first == null);}//---------------------public void insertInOrder(int iData, double dData){Link newLink = new Link(iData, dData);Link previous = null; //if you write like this: previous=first, will executed forever;Link current = first;while(current!=null && current.iData<newLink.iData){previous = current;current = current.next;  // go to next item}if(previous==null){first = newLink;}else {previous.next = newLink;}newLink.next = current;}//-----------------------------------------------------------------------public void insertFirst(int iData, double dData){Link newLink = new Link(iData, dData);Link current = first;if(first==null){first = newLink;}else{first = newLink;newLink.next = current;}}//-----------------------------------------------------------------------public void displayList(){Link current = first;if(current == null){System.out.println("Your list is empty, please show something!");}else{System.out.println("List in order (front-->rear): ");while(current!=null){current.displayLink();current = current.next;}System.out.println("");}}}public class LinkListApp{public static void  main(String[] args){LinkList theList = new LinkList(); //make new listtheList.insertInOrder(189,256.66); //insert four items, will be in an increasing ordertheList.insertInOrder(12,23.66);    theList.insertInOrder(4,23.66); theList.insertInOrder(5,23.66);theList.displayList();//display list}}

插入四个数据项后,在Eclipse中的运行效果如下:


0 0
原创粉丝点击