【双向链表的模拟实现】
由于上一篇文章已经详细讲述了单向链表的功能及模拟实现,所以双向链表这里就不在赘述, 主要讲解双向链表与单向链表的区别,以及其代码实现
1. 单向链表与双向链表的区别
-
单向链表
-
双向链表
2. 代码实现
2.1 链表的头插
public void addFirst(int data) {
listnode p=new listnode(data);
if(isempty()){
head=last=p;
}else{
head.pre=p;
p.next=head;
head=p;
}
}
2.2 链表的尾插
public void addLast(int data) {
listnode p=new listnode(data);
if(isempty()){
head=p;
}else{
last.next=p;
p.pre=last;
last=p;
}
}
2.3 链表的长度
public int size() {
listnode pcur=head;
int count=0;
while(pcur!=null){
pcur=pcur.next;
count++;
}
return count;
}
2.4 链表的打印
public void display() {
listnode pcur=head;
while(pcur!=null){
System.out.print(pcur.val+" ");
pcur=pcur.next;
}
System.out.println();
}
2.4 在指定位置插入
public void addIndex(int index, int data) {
listnode p=new listnode(data);
if(index==0){
addFirst(data);
return;
}
if(index==size()){
addLast(data);
return;
}
//找到下标为index的节点
listnode pcur=head;
for (int i = 0; i < index; i++) {
pcur= pcur.next;
}
p.next=pcur;
p.pre=pcur.pre;
pcur.pre.next=p;
pcur.pre=p;
}
2.5 查找
public boolean contains(int key) {
listnode pcur=head;
while(pcur!=null){
if(pcur.val==key){
return true;
}
pcur=pcur.next;
}
return false;
}
2.6 删除第一个出现的节点
public void remove(int key) {
listnode pcur=head;
if(pcur==null) return;
if(pcur.val==key){
head=pcur.next;
pcur=null;
return;
}
while(pcur.next!=null){
if(pcur.val==key){
pcur.pre.next=pcur.next;
pcur.next.pre=pcur.pre;
pcur.pre=pcur.next=null;
return;
}
pcur=pcur.next;
}
if(pcur.val==key){
last=last.pre;
last.next=null;
pcur.pre=null;
}
}
2.7 删除出现的所有节点
public void removeAllKey(int key) {
listnode pcur=head;
if(pcur==null) return;
while(pcur.val==key){
head=pcur.next;
pcur=head;
}
while(pcur.next!=null){
if(pcur.val==key){
pcur.pre.next=pcur.next;
pcur.next.pre=pcur.pre;
}
pcur=pcur.next;
}
if(pcur.val==key){
last=last.pre;
last.next=null;
pcur.pre=null;
}
}
2.8 清空链表
public void clear() {
//遍历逐一释放
while(head!=null){
listnode pcur=head;
head=head.next;
pcur=null;
}
}
3. 正确使用模拟双向链表
到这里上面的基础功能已经全部实现,现在就开始使用一下。
main方法如下所示:
public static void main(String[] args) {
MydoubleLinkedlist l=new MydoubleLinkedlist();
//头插
l.addFirst(1);
l.addFirst(2);
l.addFirst(3);
l.addFirst(4);
//尾插
l.addLast(5);
l.addLast(5);
l.addLast(5);
//指定位置插入
l.addIndex(3,9);
l.addIndex(0,10);
l.addIndex(l.size(), 33);
System.out.println("插入数据后:");
l.display();
System.out.println("是否包含5:"+l.contains(5));
System.out.println("是否包含32:"+l.contains(32));
//删除出现的所有节点
System.out.print("删除所有的5后:");
l.removeAllKey(5);
l.display();
//清空链表
System.out.println("清空链表后:");
l.clear();
l.display();
}
结果:
该文章到这里就结束了,希望对你有所帮助!