关于双链表的问题解决
import java.time.chrono.MinguoDate;
class Node{
public int data;
public Node prev;//前驱信息
public Node next;
public Node(int data){
this.data=data;
}
}
public class MyLinkedList {
/*
双向链表
相较于单链表,双向链表每个节点会有前一个节点的前驱信息prev
*/
public Node head;//标志双链表的头
public Node tail;//标志双链表的尾
//头插法
public void addFirst(int data) {
Node node = new Node(data);
if (this.head == null) {
this.head = node;
this.tail = node;
} else {
node.next = this.head;
this.head.prev = node;
this.head = node;//头节点改为node
}
}
//打印
public void display() {
Node node = this.head;
while (node != null) {
System.out.println(node.data);
node = node.next;
}
}
//尾插法
public void addLast(int data) {
Node node = new Node(data);
if (this.head == null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
node.prev = this.tail;
this.tail = node;
}
}
//查找是否包含关键字key是否在单链表当中
public boolean contains(int key) {
Node cur = this.head;
while (cur != null) {
if (cur.data == key) {
return true;
}
cur = cur.next;
}
return false;
}
//求双链表的长度
public int size() {
Node cur = this.head;
int count = 0;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
//检查Index的合法性
public void checkIndex(int index) {
if (index < 0 || index > size()) {
throw new RuntimeException("index不合法");
}
}
//search找到Index的位置
public Node search(int index) {
Node cur = this.head;
while (index != 0) {
cur = cur.next;
index--;
}
return cur;
}
//任意位置插入,第一个数据节点为0号下标
public void addIndex(int index, int data) {
checkIndex(index);
Node cur = search(index);
if (index == 0) {
addFirst(data);
return;
}
if (index == size()) {
addLast(data);
return;
}
Node node = new Node(data);
node.next = cur;
node.prev = cur.prev;
cur.prev.next = node;
cur.prev = node;
}
//删除第一次出现key的节点,找到返回要删除的数字,找不到返回-1
public int remove(int key) {
Node cur = this.head;
while (cur != null) {
if (cur.data == key) {//用每个节点的data与key相比较
int oldData = cur.data;//定义oldData保留头节点的data
if (cur == this.head) {//删除的数字是头节点
this.head = this.head.next;//将头节点的引用给下一个节点
this.head.prev = null;//写一个节点的prev置为空
} else {//要删出的不是头节点
cur.prev.next = cur.next;//将要删除的头节点前一个节点的next改为删除节点写一个节点的next
if (cur.next != null) {//判断删除的位置是否为最后一个节点
cur.next.prev = cur.prev;//不是最后一个节点,把删除节点的prev赋值给写一个节点的prev
} else {
this.tail = cur.prev;//最后一个节点,直接把删除节点改为尾节点
}
}
return oldData;//返回头节点data
}
cur = cur.next;
}
return -1;
}
//删除包含所有key的节点
public int removeAllKey(int key) {
Node cur = this.head;
while (cur != null) {
if (cur.data == key) {
int oldData = cur.data;
if (cur == this.head) {
this.head = this.head.next;
if (this.head != null){
this.head.prev = null;
}
} else {//要删出的不是头节点
cur.prev.next = cur.next;
if (cur.next != null) {
cur.next.prev = cur.prev;
} else {
this.tail = cur.prev;
}
}
return oldData;
}
cur = cur.next;
}
return -1;
}
//删除所有节点,双链表需要一个节点一个节点进行释放
public void clear(){
while (this.head!=null){
Node cur=this.head.next;
this.head.prev=null;
this.head.next=null;
this.head=cur;
}
}
}