}
package doublelinkedlistwithcycleandsentry;
public class DoubleLinkedListWithSentry<T extends Comparable<T>> {
//哨兵
private final DNode<T> sentry=new DNode<T>();
private DNode<T> head;
public DNode<T> getHead() {
return head;
}
public DoubleLinkedListWithSentry(DNode<T> head) {
this.head = head;
}
public DoubleLinkedListWithSentry() {
this.head=sentry;
this.head.setNext(head);
this.head.setPre(head);
}
//插入节点
public void insertData(T data){
DNode<T> element=new DNode<T>(data);
element.setNext(this.head.getNext());
this.head.getNext().setPre(element);
this.head.setNext(element);
element.setPre(head);
}
//插入的位置是从1开始的
public void insertData(T data,int pos){
if(pos<1) return ;
int len=this.size(this.head);
if(pos>len)pos=len;
DNode<T> node=this.head;
DNode<T> element=new DNode<T>(data);
for(int i=1;i<pos;i++){
node=node.getNext();
}
element.setNext(node.getNext());
node.getNext().setPre(element);
node.setNext(element);
element.setPre(node);
}
//删除元素
public boolean deleteData(T data){
DNode<T> node=this.head;
DNode<T> element=new DNode<T>(data);
DNode<T> prenode=null;
while(!node.getNext().equals(this.head)){
prenode=node;
node=node.getNext();
if(node.equals(element)){
prenode.setNext(node.getNext());
node.getNext().setPre(prenode);
node.setNext(null);
node.setPre(null);
node=null;
return true;
}
}
return false;
}
//删除指定位置的元素 第一个元素是从1开始的
public void deleteDataByPos(int pos){
if(pos<1)return ;
int len=this.size(this.head);
if(pos>len)pos=len;
DNode<T> node=this.head;
for(int i=1;i<pos;i++){
node=node.getNext();
}
node.setNext(node.getNext().getNext());
node.getNext().getNext().setPre(node);
}
//循环链表的长度
public int size(){
return this.size(this.head);
}
private int size(DNode<T> head){
DNode<T> node=head.getNext();
int count=0;
while(node!=this.head){
count++;
node=node.getNext();
}
return count;
}
//遍历链表
public void traverse(){
this.traverse(this.head);
}
private void traverse(DNode<T> head){
DNode<T> node=head.getNext();
while(node!=head){
System.out.print(node.getData()+" ");
node=node.getNext();
}
System.out.println();
}
}