Java数据结构(四):线性表之双向链表
2015-07-01 15:25
417 查看
java实现简单的双向链表,代码如下:
package datastructure.linear.linked; import datastructure.exception.StructureException; import datastructure.linear.AbstractList; /** * @Description 双向链表实现 * @author mastery * @Date 2015年6月30日下午9:11:51 */ public class BidirectionalLinkedList<T> extends AbstractList<T> { class Node<T1> { /** * 数据域 */ T1 element; /** * 指向前驱结点的指针 */ Node<T1> prior; /** * 指向后继结点的指针 */ Node<T1> next; public Node(Node<T1> next) { super(); this.prior = next; this.next = next; } public Node(T1 element, Node<T1> prior, Node<T1> next) { super(); this.element = element; this.prior = prior; this.next = next; } } private Node<T> head; private Node<T> currentNode; public BidirectionalLinkedList() { head = currentNode = new Node<T>(null); size = 0; } /** * 得到当前下标对应的结点 * * @param index * @throws StructureException */ public void indexNodeToCurrent(int index) throws StructureException { currentNode = head; if (index < -1 || index > size - 1) { throw new StructureException("index参数异常!"); } if (index == -1) { return; } currentNode = head.next; int j = 0; while (currentNode != null && j < index) { currentNode = currentNode.next; j++; } } @Override public void insert(int index, T t) throws StructureException { if (index < 0 || index > size) { throw new StructureException("index参数异常!"); } // 得到当前下标的上一个结点 indexNodeToCurrent(index - 1); Node<T> insertNode = new Node<T>(t, currentNode, currentNode.next); if (currentNode.next != null) { // 将新元素生成结点插入到当前结点下 currentNode.next.prior = insertNode; } currentNode.next = insertNode; size++; } @Override public void delete(int index) throws StructureException { if (isEmpty()) { throw new StructureException("链表为空"); } if (index < 0 || index > size) { throw new StructureException("index参数异常"); } indexNodeToCurrent(index - 1); Node<T> twoNextNode = currentNode.next.next; if (twoNextNode != null) { twoNextNode.prior = currentNode; } currentNode.next = twoNextNode; size--; } @Override public T get(int index) throws StructureException { if (isEmpty()) { throw new StructureException("链表为空"); } if (index < 0 || index > size) { throw new StructureException("index参数异常!"); } indexNodeToCurrent(index); return currentNode.element; } }
相关文章推荐
- Java数据结构(三):线性表之单链表
- 中国大学MOOC-陈越、何钦铭-数据结构基础习题——总结
- Java数据结构(二):线性表之顺序表
- 逆波兰法求解数学表达示(C++) 分类: C/C++ 数据结构与算法 2015-07-01 14:41 128人阅读 评论(1) 收藏
- 算法与数据结构八日谈之一——图论算法
- 数据结构--栈和队列
- 《数据结构与算法分析c++描述》读书笔记四——伸展树、b+树
- 数据结构--二叉堆、d堆、左式堆和斜堆
- 数据结构基础温故-1.线性表(中)
- 常见数据结构算法边学边记
- 数据结构-中序转后序
- sizzle.js学习笔记利用闭包模拟实现数据结构:字典(Map)
- 【数据结构】链表
- get(index) set(index value), setAll(value)都为O(1)的数据结构
- 数据结构的基本概念
- 数据结构常见面试题
- java 数据结构
- 数据结构链表的操作集合(建立,遍历,插入,删除,排序,长度,空判断等)
- 数据结构顺序表的操作全集(创建,遍历,插入,删除,排序等等)
- swift篇第一期:简单的数据结构