MyLinkedList

/**
 * 节点类
 * @author JP
 * 
 */
class Node {
	Object value;//节点元素值
	Node pre;//上一个节点
	Node next;//下一个节点

	public Node(Object value) {
		this.value = value;
	}
}

/**
 * 链表类
 * @author JP
 *
 */
public class MyLinkedList {
	Node cur;//目前指向的节点
	Node head;//头结点
	Node end;//尾节点
	int size = 0;

	/**
	 * 实例化头节点和尾节点
	 */
	public MyLinkedList() {

		head = new Node("head");
		end = new Node("end");
		//设置头尾相连
		head.next = end;
		end.pre = head;
	}

	/**
	 * 增长操做
	 * @param value
	 */
	public void add(Object value) {
		//判断当前插入的元素是不是第一个元素
		if (cur == null) {
			cur = new Node(value);
			head.next = cur;
			cur.pre = head;

		} else {
			Node node = new Node(value);
			cur.next = node;
			node.pre = cur;
			cur = node;//将cur元素设置为当前插入的节点
		}
		cur.next = end;
		end.pre = cur;
		size++;
	}

	/**
	 * 在指定位置插入元素,第一个元素的下标为0
	 * @param index
	 * @param value
	 * @throws Exception
	 */
	public void add(int index, Object value) throws Exception {

		//判断当前要插入的元素是否为链表的最后一个元素
		if (index == size) {
			this.add(value);
		} else {
			Node tmp = this.get(index);//当前index位置所对应的节点
			Node node = new Node(value);//当前要插入的节点

			tmp.pre.next = node;
			node.pre = tmp.pre;
			node.next = tmp;
			tmp.pre = node;
		}
		size++;
	}

	/**
	 * 删除指定位置的元素,第一个元素的下标为0
	 * @param index
	 * @throws Exception 
	 */
	public void remove(int index) throws Exception {

		Node tmp = this.get(index);//当前index位置所对应的节点
		tmp.pre.next = tmp.next;
		tmp.next.pre = tmp.pre;
		size--;
	}

	/**
	 * 获取指定位置的节点元素
	 * @param index
	 * @return
	 * @throws Exception 
	 */
	public Node get(int index) throws Exception {
		if (index < 0 || index >= size) {
			throw new Exception("数组下标越界!");
		}
		Node node = head.next;
		for (int i = 1; i <= index; i++) {

			node = node.next;//迭代为下一个节点
		}
		return node;
	}

	/**
	 * 将链表转化成数组
	 * @return
	 */
	public Object[] toArray() {
		Object[] arr = new Object[size];
		Node node = head.next;
		for (int i = 0; i < arr.length; i++) {

			arr[i] = node.value;
			node = node.next;//迭代为下一个节点
		}

		return arr;
	}

	public static void main(String[] args) throws Exception {
		MyLinkedList list = new MyLinkedList();
		list.add(1);
		list.add(2);

		list.add(3);
		list.add(4);
		//list.remove(4);
		//list.add(4,"a");
	
		Object[] arr = list.toArray();
		for (Object obj : arr) {
			System.out.println(obj);
		}

	}
}
相关文章
相关标签/搜索