import java.util.ArrayList;
public class DLinkDemo {
interface List {
public void insert(int i, Object obj) throws Exception;
public Object delete(int i) throws Exception;
// public Object update(int i, Object obj) throws Exception;
public Object getData(int i) throws Exception; // 获取i元素
public int size(); // 表数据总数
public boolean isEmpty();
}
class TNode {
TNode prior;
Object element;
TNode next;
TNode(TNode nextval) {
prior = nextval;
next = nextval;
}
TNode(TNode priorval, Object obj, TNode nextval) {
prior = priorval;
element = obj;
next = nextval;
}
public TNode getPrior() {
return prior;
}
public void setPrior(TNode priorval) {
prior = priorval;
}
public TNode getNext() {
return next;
}
public void setNext(TNode nextval) {
next = nextval;
}
public Object getElement() {
return element;
}
public void setElement(Object obj) {
element = obj;
}
public String toString() {
return element.toString();
}
}
class DoubleLinkList implements List {
TNode head;
TNode current;
int size;
public DoubleLinkList() {
head = current = new TNode(null);
head.next = head;
head.prior = head;
size = 0;
}
/**
* 定位成员函数index(int i)的实现
*
* 循环从头开始查找,循环的条件是:1.定位完成j==i;2.链表查找结束了.
*
* @param i
*/
public void index(int i) throws Exception {
if (i < -1 || i > size - 1) {
throw new Exception("i error in Index");
}
if (i == -1)
return;
current = head.next;
int j = 0;
while (current != head && j < i) {
current = current.next;
j++;
}
}
@Override
public void insert(int i, Object obj) throws Exception {
if (i < 0 || i > size) {
throw new Exception("i error in INSERT.");
}
index(i - 1);
current.setNext(new TNode(current.getNext(), obj, current.next
.getPrior()));
current.next.next.setPrior(current.next.getNext());
size++;
}
@Override
public Object delete(int i) throws Exception {
if (size == 0) {
throw new Exception("Link Blank in DELETE.");
}
if (i < 0 || i > size - 1) {
throw new Exception("i error in DELETE.");
}
index(i - 1);
Object obj = current.next.getElement();
current.setNext(current.next.next);
current.next.setPrior(current.getNext());
size--;
return obj;
}
@Override
public Object getData(int i) throws Exception {
if (i < -1 || i > size - 1) {
throw new Exception("i error in getData.");
}
index(i);
return current.getElement();
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
}
public static void main(String[] args) {
DLinkDemo x = new DLinkDemo();
DoubleLinkList doubleLinkList = x.new DoubleLinkList();
int n = 10;
try{
for (int i = 0; i < n; i++){
doubleLinkList.insert(i, new Integer(i + 1));
}
doubleLinkList.delete(4);
for (int i = 0; i < doubleLinkList.size; i++){
System.out.print(doubleLinkList.getData(i) + "->");
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
1->2->3->4->6->7->8->9->10->
双向链表
最新推荐文章于 2024-02-04 11:36:52 发布