博客列表 >用java实现一个链表类

用java实现一个链表类

bingbing的博客
bingbing的博客原创
2018年09月21日 17:03:221618浏览

实例

//用java实现一个链表类
import javax.management.RuntimeErrorException;

public class MyList {

	private static class Node {			//内部类,节点
		Object data;					//数据
		Node next;						//下一个节点的引用
		public Node(Object data){		//构造方法,为data赋值
			super();
			this.data = data;
			this.next = null;
		}
	}
	Node head;							//头节点
	public MyList() {					//链表的构造方法
		head = null;
	}
	
	public void clear() {				//清楚链表
		head = null;
	}
	
	public void travel() {				//遍历打印链表
		Node p = head;
		while (p != null) {
			System.out.println(p.data);
			p = p.next;
		}
	}
	
	public boolean isEmpty() {			//判断是否为空
		return head == null;
	}
	
	public int size() {					//得到节点的个数
		Node p =head;
		int sum= 0;
		while (p != null) {
			sum++;
			p = p.next;
		}
		return sum;
	}
	
	//在指定位置插入元素,下标从0开始
	public void insert(Object d, int pos) {
		if (pos < 0 || pos >size()) {		//下标异常
			throw new RuntimeErrorException( null, "下标出错");
		}
		Node newNode = new Node(d);
		if (pos == 0) {						//从第一个位置插入节点
			newNode.next = head;			//把新节点的
			head = newNode;
		}else if (pos >= size() - 1) {		//从最后的位置插入节点
			get(size() - 1).next = newNode; 	//把最后一个节点的next指向新节点
		}else {
			newNode.next = get(pos);		//把新节点的next指向pos位置的节点
			get(pos - 1).next = newNode;	//把pos-1节点的next指向新节点
		}
	}
	
	//获取特定位置上的节点
	public Node get(int pos) {
		if (pos < 0 || pos >size()) {		//下标异常
			throw new RuntimeErrorException( null, "下标出错");
		}
		if (pos == 0) {						//如果为0,直接返回head
			return head;
		}
		Node p = head;						//从head开始,顺摸到指定位置
		for (int i = 0; i < pos; i++) {
			p = p.next;
		}
		return p;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyList list = new MyList();			//创建List对象
		list.insert(10, 0);					//在0位置插入元素
		list.insert(20, 1);					//在1位置插入元素
		list.insert(30, 0);					//在0位置插入元素
		list.insert(40, 1);					//在1位置插入元素
		list.travel();						//遍历打印链表
	}

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议