自定異常類
Java代碼
public class MyException extends Exception {
public MyException(){};
public MyException(String msg){
super(msg);
}
}
鏈表結點對像
Java代碼
public class Node {
public Node previou=null;//前結點指針
public Node next=null; //後結點指針
public Object value;//結點值
Node(Object value){
this
}
}
鏈表對像
Java代碼
public class DoubleLinked {
private Node head;//鏈表頭
DoubleLinked(){
}
/**
* 判斷是否還有下一個結點
* @param node
* @return
*/
public boolean hasNext(Node node){
if(node
return false;
return true;
}
/**
* 判斷是否有上一個結點
* @param node
* @return
*/
public boolean hasPrev(Node node){
if(node
return false;
return true;
}
/**
* 獲取鏈表頭元素
* @return
* @throws MyException
*/
public Node getHead() throws MyException{
if(head==null){
throw new MyException(
}
return head;
}
/**
* 獲取上一個接點
* @param node
* @return
*/
public Node getPrev(Node node){
return node
}
/**
* 獲取下一個結點
* @param node
* @return
*/
public Node getNext(Node node){
return node
}
/**
* 根據索引獲取結點
* @param index
* @return
* @throws MyException
*/
public Node getNode(int index) throws MyException{
Node curNode=null;
Node next=null;
Node node=null;
if(head==null){
throw new MyException(
}else{
curNode=head;
for(int i=
if(curNode==null){
throw new MyException(
}else{
node=curNode;
if(hasNext(curNode)){
next=curNode
curNode=next;
}else{
curNode=null;
}
}
}
}
return node;
}
/**
* 獲取最後一個結點
* @return
* @throws MyException
*/
public Node getLast() throws MyException{
Node curNode=null;
Node next=null;
Node last=null;
boolean flag=true;
if(head==null){
throw new MyException(
}else{
curNode=head;
while(flag){
if(hasNext(curNode)){
next=curNode
curNode=next;
}else{
last=curNode;
flag=false;
}
}
}
return last;
}
/**
* 在鏈表頭添加新結點
* @param node
*/
public void addHead(Node node){
if(head==null){
head=node;
}else{
node
head
head=node;
}
}
/**
* 在鏈表末尾處添加新結點
* @param node
* @throws MyException
*/
public void addLast(Node node) throws MyException{
if(head==null){
head=node;
}else{
Node last=this
last
node
}
}
/**
* 在鏈表中間插入新結點
* @param node
* @throws MyException
*/
public void insertNode(int index
Node indexNode=this
Node prev=indexNode
prev
node
node
indexNode
}
/**
* 刪除鏈表頭結點
* @return
* @throws MyException
*/
public Node deleteHead() throws MyException{
Node head=this
if(hasNext(head)){
Node next=head
this
next
}
return head;
}
/**
* 刪除鏈表的最後一個結點
* @return
* @throws MyException
*/
public Node deleteLast() throws MyException{
Node last=this
Node prev=last
if(prev==null){
this
}else{
prev
}
return last;
}
/**
* 根據索引刪除鏈表結點
* @param index
* @return
* @throws MyException
*/
public Node deleteNode(int index) throws MyException{
Node node=this
Node prev=node
Node next=node
if(prev==null && next!=null){
this
next
}
if(prev!=null && next==null){
prev
}
if(prev==null && next==null){
this
}
if(prev!=null && next!=null){
prev
next
}
return node;
}
} :!:
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26531.html