《Java数据结构与算法》笔记-CH5-链表-3双端链表

/**
 * 双端链表的实现
 */
class LinkA {
	public long dData;
	public LinkA next;

	public LinkA(long d) {
		dData = d;
	}

	public String toString() {
		return "[" + dData + "]";
	}

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

class FirstLastList {
	private LinkA first;// 头部
	private LinkA last;// 尾部

	public FirstLastList() {
		first = null;
		last = null;
	}

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

	/**
	 * 在头部插入节点
	 */
	public void insertFirst(LinkA l) {
		if (isEmpty())
			last = l;
		l.next = first;
		first = l;
	}

	/**
	 * 在尾部插入节点
	 * 
	 * @param l
	 */
	public void insertLast(LinkA l) {
		if (isEmpty())
			first = l;
		else
			last.next = l;
		last = l;
	}

	/**
	 * 从头部删除一个节点
	 * 
	 * @return
	 */
	public long deleteFirst() {
		long temp = first.dData;
		if (first.next == null)
			last = null;
		first = first.next;
		return temp;
	}

	public String toString() {
		if (isEmpty())
			return "{}";
		LinkA current = first;
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		while (current != null) {
			sb.append(current.toString()).append(",");
			if (current.next == null)
				break;
			else
				current = current.next;
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append("}");
		return sb.toString();
	}

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

public class FirstLastListDemo {
	public static void main(String[] args) {
		FirstLastList fll = new FirstLastList();
		for (int i = 1; i < 10; i++) {
			System.out.println("插入:"+i);
			if (i % 2 == 0)//i为偶数调用insertFirst
				fll.insertFirst(new LinkA(i));
			else//i为基数调用insertLast
				fll.insertLast(new LinkA(i));
			fll.displayList();
		}
		System.out.println("插入完毕开始从头部删除");
		while(!fll.isEmpty()){
			fll.deleteFirst();
			fll.displayList();
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值