Java双連鎖表の添削は基本操作を調べます。
4192 ワード
データ構造を復習します。コードは一番いい説明です。
前のページにシングルチェーン表を書きました。時間があるうちにダブルチェーンも一緒に書いて、ダブルチェーン類をカプセル化して、異常な処理をしました。それがもっと実用的な応用に合うようにします。
ノードクラス:
前のページにシングルチェーン表を書きました。時間があるうちにダブルチェーンも一緒に書いて、ダブルチェーン類をカプセル化して、異常な処理をしました。それがもっと実用的な応用に合うようにします。
ノードクラス:
public class Node {
private Object object;
private Node next;
private Node pre;
public Node(Object object) {
this.object = object;
next = null;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
}
双チェーン類:public class DoubleLinkedList {
// 、 、 , tail、size
private Node head;
private Node tail;
private int size;
public DoubleLinkedList() {
size = 0;
}
/**
*
* @param o
*/
public void addNewHead(Object o){
Node node = new Node(o);
if (head != null){
node.setNext(head);
head.setPre(node);
}
head = node;
size++;
}
/**
*
*/
public void deleteHead(){
if (head.getNext()==null){
head = null;
return;
}
head = head.getNext();
head.setPre(null);
size--;
}
/**
*
* @param o
*/
public void addNewTail(Object o){
Node node = new Node(o);
if (head == null){
addNewHead(o);
return;
}
if(tail==null){
setTail();
}
tail.setNext(node);
node.setPre(tail);
setTail();
size++;
}
/**
*
*/
public void deleteTail(){
if (head==null){
return;
}
if (tail==null){
setTail();
}
tail=tail.getPre();
tail.setNext(null);
size--;
}
/**
* index
* @param o
* @param index
*/
public void add(Object o,int index){
if (index>size){
throw new ArrayIndexOutOfBoundsException();
}else if (index==0){
addNewHead(o);
return;
}else if(index==size){
addNewTail(o);
return;
}
Node temp = head;
while (index>1){
temp = temp.getNext();
index--;
}
Node node = new Node(o);
temp.getNext().setPre(node);
node.setNext(temp.getNext());
temp.setNext(node);
node.setPre(temp);
size++;
}
/**
* index
* @param index
*/
public void delete(int index){
if (index>=size){
throw new ArrayIndexOutOfBoundsException();
}else if (index==0){
deleteHead();
return;
}else if(index==size-1){
deleteTail();
return;
}
Node temp = head;
while (index>1){
temp = temp.getNext();
index--;
}
temp.getNext().getNext().setPre(temp);
temp.setNext(temp.getNext().getNext());
size--;
}
/**
* , index ,
*/
/**
* ,
*/
public void printAll(){
Node temp = head;
while (temp.getNext()!=null){
System.out.print(temp.getObject().toString()+"<=>");
temp = temp.getNext();
}
System.out.print(temp.getObject().toString());
System.out.println();
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public int getSize() {
return size;
}
public Node getTail() {
return tail;
}
/**
*
*/
public void setTail() {
if (head==null){
return;
}
tail = head;
while (tail.getNext()!=null){
tail = tail.getNext();
}
}
}
間違いがあったら、訂正してください。