链表2

package ChapterFive;

class Link<E> {

	public E data;

	public Link<E> next;

	public Link(E data) {
		this.data = data;
	}
}

class LinkList<E> {

	public Link<E> first;
	//链表中数据项的个数
	public int size;

	public LinkList() {
		first = null;
		size = 0;
	}
	//在表头插入新的数据
	public void insertFirst(E value) {
		Link<E> link = new Link<E>(value);
		link.next = first;
		first = link;
		size++;
	}
	//判断链表是否为空
	public boolean isEmpty() {
		return size == 0;
	}
	//删除表头
	public Link<E> deleteFirst() {
		Link<E> temp = first;
		first = first.next;
		size--;
		return temp;
	}
	//输出链表中的所有数据
	public void display() {
		Link<E> curr = first;
		while (curr != null) {
			System.out.print(curr.data + " ");
			curr = curr.next;
		}
		System.out.println();
	}
	//返回链表中数据项的个数
	public int size() {
		return size;
	}
	//获取从头至尾的第i个数据项
	public Link<E> get(int i) {
		if (i > size() - 1 || i < 0)
			try {
				throw new IndexOutOfBoundsException();
			} catch (Exception e) {
				e.printStackTrace();
			}
		Link<E> curr = first;
		for (int n = 0; n < size(); n++) {
			if (n == i)
				return curr;
			else
				curr = curr.next;
		}
		return null;
	}
	//输出从头至尾的第i个数据项
	public void remove(int i) {
		if (i == 0)
			deleteFirst();
		else if (i == size() - 1)
			get(i - 1).next = null;
		else {
			get(i - 1).next = get(i + 1);
		}
		size--;
	}
}

public class Link_list {
	public static void main(String[] args) {
		LinkList<Long> ll = new LinkList<Long>();
		for (int i = 0; i < 10; i++) {
			Long value = (long) (Math.random() * 100);
			ll.insertFirst(value);
		}
		ll.display();
		while (!ll.isEmpty()) {
			ll.deleteFirst();
			ll.display();
		}
		System.out.println("Ok");
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值