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);
		}

	}
}

  

转载于:https://www.cnblogs.com/syjp/p/11082955.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值