Java数据结构和算法中文第二版.pdf 代码
Link.java package com.ch5.sortedlist; public class Link { private long dData ; private Link next ; public Link(){ } public Link(long dData){ this.dData = dData ; } public long getdData() { return dData; } public void setdData(long dData) { this.dData = dData; } public Link getNext() { return next; } public void setNext(Link next) { this.next = next; } public void displayLink(){ System.out.print(dData+ " "); } } SortedList.java package com.ch5.sortedlist; public class SortedList { private Link first ; public SortedList(){ first = null ; } public boolean isEmpty(){ return (first == null) ; } public void insert(long key){ Link newLink = new Link(key) ; Link previous = null ; Link current = first ; while( (null != current) && current.getdData() < key ){ previous = current ; current = current.getNext() ; } if (null == previous){ first = newLink ; }else{ previous.setNext(newLink) ; } newLink.setNext(current) ; }//end insert //remove first public Link remove(){ Link temp = first ; first = first.getNext() ; return temp ; } //remove by key public Link remove(long key){ //is empty ,return null ; if (isEmpty()){ return null ; } Link current = first ; Link previous = null ; while(null != current && current.getdData() != key){ previous = current ; current = current.getNext() ; } //is first if (null == previous){ first = first.getNext() ; }else if (null != current){//else not end previous.setNext(current.getNext()) ; } return current ; } public void displayList(){ System.out.print("List (first-->last):"); Link current = first ; while (null != current){ current.displayLink() ; current = current.getNext() ; } System.out.println(" "); } } SortedListApp.java package com.ch5.sortedlist; public class SortedListApp { /** * @param args */ public static void main(String[] args) { SortedList theSortedList = new SortedList() ; theSortedList.insert(20) ; theSortedList.insert(50) ; theSortedList.insert(40) ; theSortedList.insert(35) ; theSortedList.insert(100) ; theSortedList.displayList() ; theSortedList.remove() ; theSortedList.displayList() ; theSortedList.insert(20) ; theSortedList.displayList() ; theSortedList.remove(40) ; theSortedList.displayList() ; } }