《Java数据结构与算法》笔记-CH5-链表-6实现有序链表

//有序链表
/**
 * 节点类
 */
class Node {
	public long data;
	public Node next;

	public Node(long d) {
		this.data = d;
	}

	public String toString() {
		return String.valueOf(data);
	}
}
/**
 * 有序链表类
 */
class SortedList {
	private Node first;

	public SortedList() {
		first = null;
	}

	public boolean isEmpty() {
		return first == null;
	}

	public void insert(Node n) {
		Node previous = null;
		Node current = first;
		// 找到要插入的位置,应插入到当前节点的前面
		while (current != null && n.data > current.data) {// 直到最后没找到,或者找到时停止
			previous = current;
			current = current.next;
		}
		/* //previous为空,说明应该插入到第一个节点前面 
		 * if(previous == null){ 
		 * 		first = n; 
		 * 		n.next = current; 
		 * }else{//不在最开始的位置,也就是在中间或者尾部 
		 * 		previous.next = n; 
		 * 		n.next = current; 
		 * } 
		 * 都需要n.next = current;把这行提出来
		 */
		if (previous == null)
			first = n;
		else
			previous.next = n;
		n.next = current;
	}
	public Node remove(){
		Node temp = first;
		first = first.next;
		return temp;
	}
	public String toString(){
		if(isEmpty()) return "[]";
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		Node current = first;
		while(current != null){
			sb.append(current.toString()).append(",");
			current = current.next;
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		return sb.toString();
	}

	public void display() {
		System.out.println(toString());
	}
}

public class SortedListDemo {
	public static void main(String[] args) {
		int [] arr = {4,3,1,6,2};
		SortedList sl = new SortedList();
		Node n;
		for(int i=0;i<arr.length;i++){
			n = new Node(arr[i]);
			sl.insert(n);
			System.out.println("插入"+n.toString()+"后,有序链表为:"+sl.toString());
		}
		while(!sl.isEmpty()){
			System.out.print("移除头部:"+sl.remove());
			System.out.print(",有序链表为:");
			sl.display();
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值