关闭

有序链表

标签: nullinsertclass数据结构string算法
504人阅读 评论(0) 收藏 举报
分类:
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() ;
		
	}

}


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:352238次
    • 积分:3689
    • 等级:
    • 排名:第8820名
    • 原创:74篇
    • 转载:31篇
    • 译文:0篇
    • 评论:62条
    最新评论