双端链表是一种特殊的链表,它和普通链表的差别在于,
双端列表的链头不止含有对下一个结点的引用,还含有对链尾结点的引用,
所以双端链表可以对链头和链尾进行插入查找。
由于前面已经详细地写过链表常用方法的实现,这里就不在赘述。
package com.example.demo;
/**
* @Description:双端列表
* @CreateDate: Created in 2018/10/10 18:45
* @Author: <a href="https://blog.csdn.net/pbrlovejava">arong</a>
*/
public class FirstLastLink {
//第一个链结点
private Link first;
//最后一个链结点
private Link last;
//含参构造,将first和last赋为null
public FirstLastLink(){
this.first = null;
this.last = null;
}
//判断链表是否为空
public boolean isEmpty(){
return (this.first == null);
}
//插入链头结点
public void insertFirst(int data){
Link linkFirst = new Link(data);
if(isEmpty()){
//当前链表为空
this.first = linkFirst;//linkFirst(first)
this.last = linkFirst;//linkFirst(last)
}else{
linkFirst.next = this.first;//linkHead -> old first
this.first = linkFirst;//new first -> linkHead
}
}
//插入链尾
public void insertLast(int data){
Link linkLast = new Link(data);
if(isEmpty()){
this.first = linkLast;
this.last = linkLast;
}else{
this.last.next = linkLast;//old last -> new last
this.last = linkLast;//linkLast(new last)
}
}
//遍历链表
public void displayLinkList(){
Link current = this.first;//从链头开始遍历
while (current != null){
//当前链结点不为空即输出内容
current.displayLink();
//将当前链结点指向下一个链结点
current = current.next;
}
}
//删除链头
public void deleteFirst(){
if(isEmpty()){
System.out.println("空链表");
}else if(this.first.next == null){
//链表中只有一个表头
this.first = null;
this.last = null;
}
}
//查找链表中的结点
public Link find(int key){
Link current = this.first;//将当前指向first结点
while(current.next != null){
//链表不为空时
if(current.data != key ){
//不是该数据,将current向下移动
current = current.next;
}else if(current.data == key){
System.out.println("已经找到该结点");
return current;
}
}
System.out.println("没有找到该节点");
return null;//没有找到链结点
}
//链结点的删除
public void delete(int key){
Link current = this.first;
Link pre = null;
while(current.next != null){
if(current.data == key && current == this.first){
//要删除的是链头
this.first = current.next;
}else if(current.data != key){
pre = current;//将当前链结点赋值为链前结点
current = current.next;
}else if(current.data == key && current.next == null){
//要删除的是链尾
current = null;//
this.last = pre;
System.out.println("已删除含"+key+"的链结点");
return;
}else if(current.data == key){
//找到要删除的current
pre.next = current.next;//删除,连接两个链结点 pre.next->current.next
System.out.println("已删除含"+key+"的链结点");
return;
}
}
System.out.println("找不到链结点");
}
//链表结点
static class Link{
public int data;//结点中存储的数据
public Link next;//下一个结点
//含参构造方法
public Link(int data){
this.data = data;
}
//输出链结点
public void displayLink(){
System.out.print(this.data+"->");
}
}
}