(一)、什么是无头双向链表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/be587fea00cc89bebaf2a324e5426c29.png)
二、双向链表的操作
(一)、带有前驱的节点。
class ListNode{
public int val;
public ListNode prev;
public ListNode next;
public ListNode(int val){
this.val=val;
}
}
(二)、定义头尾节点
public class MyLinkedList {
public ListNode head;
public ListNode last;
public void display(){
ListNode cur=this.head;
while (cur!=null){
System.out.print(cur.val+" ");
cur=cur.next;
}
System.out.println();
}
}
(三)得到双链表的长度
public int size(){
ListNode cur=this.head;
int count=0;
while (cur!=null){
count++;
cur=cur.next;
}
return count;
}
(四)、头插法
public void addFirst(int data){
ListNode node=new ListNode(data);
if (head==null){
this.head=node;
this.last=node;
return;
}else {
node.next=this.head;
this.head.prev=node;
this.head=node;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e175e9accf37648b90efda54976abf3c.png)
(五)尾插法
public void addLast(int data){
ListNode node=new ListNode(data);
if (last==null){
this.head=node;
this.last=node;
}else {
this.last.next=node;
node.prev=this.last;
this.last=node;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/70df87fcb59b868702acb92a62c16e71.png)
(六)索引位置
public ListNode searchIndex(int index){
ListNode cur=this.head;
if (index<0||index>size()){
System.out.println("输入不合法");
}
while (index!=0&&cur!=null){
cur=cur.next;
index--;
}
return cur;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/018227e5c4bbc55e917a043c1aaa418d.png)
(七)任意位置插入
public void addIndex(int index,int data){
ListNode node=new ListNode(data);
if (index<0||index>size()){
System.out.println("输入不合法");
return;
}
if (index==0){
addFirst(data);
return;
}
if (index==size()){
addLast(data);
return;
}
ListNode cur=searchIndex(index);
node.next=cur.prev.next;
cur.prev.next=node;
node.prev=cur.prev;
cur.prev=node;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/982f2472cf5a39cdf056818887d17322.png)
(八) 查找是否包含关键字key
public boolean contains(int key){
ListNode cur=this.head;
while (cur!=null){
if (cur.val==key){
return true;
}
cur=cur.next;
}
return false;
}
删除第一次出现关键字为key
public void remove(int key) {
ListNode cur = this.head;
while (cur != null) {
if (cur.val == key) {
if (cur == head) {
this.head = this.head.next;
if (head!=null){
head.prev = null;
}else {
last=null;
}
} else {
cur.prev.next = cur.next;
if (cur.next != null) {
cur.next.prev = cur.prev;
} else {
last = last.prev;
}
}
return;
} else {
cur = cur.next;
}
}
}
删除所有值为key
public void removeAllKey(int key) {
ListNode cur = this.head;
while (cur != null) {
if (cur.val == key) {
if (cur == head) {
this.head = this.head.next;
if (head!=null){
head.prev = null;
}else {
last=null;
}
} else {
cur.prev.next = cur.next;
if (cur.next != null) {
cur.next.prev = cur.prev;
} else {
last = last.prev;
}
}
}
cur = cur.next;
}
}
public void clear(){
while (this.head!=null){
ListNode curNext=head.next;
head.next=null;
head.prev=null;
head=curNext;
}
last=null;
}
}