代码实现
class linkNode{
int data;
linkNode pre;
linkNode next;
linkNode(int data){
this.data=data;
}
}
public class DoublelinkList {
linkNode head;
linkNode last;
public void display(){
linkNode cur=this.head;
while(cur!=null){
System.out.println(cur.data);
cur=cur.next;
}
}
public void addFirst(int data){
linkNode node=new linkNode(data);
if(this.head==null){
this.head=node;
this.last=this.head;
}else{
node.next=this.head;
this.head.pre=node;
this.head=node;
}
}
public void addAfter(int data){
linkNode node=new linkNode(data);
if(this.head==null){
this.head=node;
this.last=this.head;
}else{
this.last.next=node;
node.pre=this.last;
this.last=node;
}
}
public int getSize(){
linkNode cur=this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
//指定Index位置插入
public void insertIndex(int index,int data){
linkNode node=new linkNode(99);
if(this.head==null){
return ;
}
if(index<0 || index>getSize()){
System.out.println("插入位置不合法");
return ;
}
if(index==0){
addFirst(data);
return ;
}
if(index==getSize()){
addAfter(data);
return;
}
linkNode cur=this.head;
while(index-->0){
cur=cur.next;
}
node.next=cur;
cur.pre.next=node;
node.pre=cur;
cur.pre=node;
}
public linkNode findKey(int key){
linkNode cur=this.head;
if(this.head==null){
return null;
}
while(cur!=null){
if(cur.data==key){
return cur;
}
cur=cur.next;
}
return null;
}
//删除表中的节点
public void deleteKey(int key){
if(this.head==null){
return ;
}
linkNode cur=findKey(key);
if(cur==this.head){
if(cur.next==null){
this.head=null;
return ;
}else{
this.head=cur.next;
cur.next.pre=null;
return ;
}
}
if(cur.next==null){
cur.pre.next=null;
this.last=cur.pre;
return;
}
cur.pre.next=cur.next;
cur.next.pre=cur.pre;
}
}
循环链表增删查图解: