您的位置:首页 > 编程语言 > Java开发

java双向链表的实现(部分功能)

2009-07-23 21:38 591 查看
]public class DoubleLinkedList {
	private Node head;
	private Node tail;
	private int size;
	
	public DoubleLinkedList() {
		head = new Node();
		tail = head;
		size = 0;
	}
	
	private class Node {
		public Object data;
		public Node next;
		public Node front;
		
		Node() {
			this.data = null;
		}
		Node(Object data) {
			this.data = data;
		}
	}
	//在链表指定的位置插入指定的元素,后插。index从0 到 size ,为0时加在head的后面
	public void add(int index, Object element) {
		if(index > size || index < 0) {
			throw new IndexOutOfBoundsException("index:" + index);
		}
		
		Node newNode = new Node(element);
		Node p = head;
		for(int i=0; i<index; i++) {
			p = p.next;
		}
		if(p.next != null){//若p不为最后一个节点
			newNode.front = p;
			newNode.next = p.next;
			p.next.front = newNode;
			p.next = newNode;
		}else{        //若p为最后一个节点
			p.next = newNode;
			newNode.front = p.front;
			tail = newNode;
		}	
		size ++;
	}
	
	//在链表的最后加入指定的元素
	public void add(Object element) {
		add(size, element);
	}
	
	//获取指定位置的元素
	public Object get(int index) {
		if(index >size || index<0) {
			throw new IndexOutOfBoundsException("index:" + index);
		}
		Node p = head;
		int i = 0;
		while(p != tail) {
			p = p.next;
			if(i == index) {
				return p.data;
			}
			i++;
		}
		return null;
	}
	
	//清空列表
	public void clear() {
		head = null;
		tail = null;
		size = 0;
	}
	public static void main(String[] args) {
		DoubleLinkedList list = new DoubleLinkedList();
		for(int i=0; i<10; i++) {
			list.add(i);
		}
		for(int i=0; i<list.size; i++) {
			System.out.print(list.get(i) + " ");
		}
	}	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: