有序链表

有序链表的java实现

分析

在大多数的有序数组的使用情况下都可以使用有序链表,且有序列表的性能要优于有序数组主要表现在连个方面
1:有序的链表插入速度快 (链表不要移动)
2:链表可以拓展到全部有效内存,而数组只能限于一个固定的大小中

话不多说直接上代码

package com.yc.Link;

//节点类
public class Link {
	private int idate;
	private double ldate;
	private Link   next;
	
	public Link(int idate, double ldate) {
		super();
		this.idate = idate;
		this.ldate = ldate;
	}
	
	public Link(int idate) {
		super();
		this.idate = idate;
	}

	public int getIdate() {
		return idate;
	}
	public void setIdate(int idate) {
		this.idate = idate;
	}
	public double getLdate() {
		return ldate;
	}
	public void setLdate(double ldate) {
		this.ldate = ldate;
	}
	public Link getNext() {
		return next;
	}
	public void setNext(Link next) {
		this.next = next;
	}

	@Override
	public String toString() {
		return "Link [idate=" + idate + ", ldate=" + ldate + ", next=" + next + "]";
	}
	
	
	
	
}

SortLink类

package com.yc.Link;

public class SortLink {
	
	private Link first;//头结点
	
	//constructor
	public SortLink() {
		first=null;
	}
	
	//移除元素只支持从头部开始移除
	public Link remove() {
		
			Link temp=first;
			
			first=first.getNext();
			return temp;
		
		
	}
	//展示链表元素
	public void display() {
		System.out.print("List -->last:");
		Link current=first;
		while(current!=null) {
			System.out.print("-->"+current.getIdate());
			current=current.getNext();
		}
		System.out.println("");
	}
	//插入元素
	public void insert(int key ) {
		Link newLink=new Link(key);
		Link previo=null;//前一个位置的结点
		Link courrent=first;//当前位置的结点
		//寻找插入位置    
		//跳出循环的courent为要插入的结点位置的前一个结点
		while(courrent!=null && courrent.getIdate()<key) {
			previo=courrent;
			courrent=courrent.getNext();
		}
		//插入的位置为头结点(即链表表头的时候)
		if(previo==null) {
			//直接插入头结点
			first=newLink;
		}else {
			//当插入的位置其他位置的时候
			
			previo.setNext(newLink);
		}
		newLink.setNext(courrent);
		
	}
	
	//测试
	public static void main(String[] args) {
		SortLink sort=new SortLink();
		
		sort.insert(8);
		sort.insert(5);
		sort.display();
		sort.insert(1);
		sort.insert(4);
		
		sort.display();
		
	}
}

运行效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值