双向环形链表带哨兵,这时哨兵既作为头,也作为尾。
package com.tfq.arithmetic.linkedlist;
import java.util.Iterator;
/**
* @author: fqtang
* @date: 2024/05/22/8:40
* @description: 环形链表
*/
public class DoublyLinkedListSentinel implements Iterable<Integer> {
private static class Node {
Node prev;//上一个节点指针
int value;//值
Node next;//下一个节点指针
public Node(Node prev, int value, Node next) {
this.prev = prev;
this.next = next;
this.value = value;
}
}
/**
* 哨兵对象
*/
private Node sentinel = new Node(null, -1, null);
public DoublyLinkedListSentinel() {
sentinel.prev = sentinel;
sentinel.next = sentinel;
}
/**
* 添加到第一个
*
* @param value -待添加值
*/
public void addFirst(int value) {
Node a = sentinel;
Node b = sentinel.next;
Node added = new Node(a, value, b);
a.next = added;
b.prev = added;
}
/**
* 向索引位置插值
*
* @param index 索引
* @param value 待插入值
*/
public void insert(int index, int value) {
Node findNode = findByIndex(index);
Node last = findNode.prev;
Node next = findNode;
Node added = new Node(last, value, next);
last.next = added;
next.prev = added;
}
/**
* 添加到最后一个
*
* @param value -待添加值
*/
public void addLast(int value) {
Node a = sentinel.prev;
Node b = sentinel;
Node added = new Node(a, value, b);
a.next = added;
b.prev = added;
}
/**
* 删除第一个元素
*/
public void removeFirst() {
Node removed = sentinel.next;
if(removed == sentinel) {
throw new IllegalArgumentException("不能删除哨兵节点,非法!");
}
Node last = sentinel;
Node next = removed.next;
last.next = next;
next.prev = last;
}
/**
* 删除最后一个元素
*/
public void removeLast() {
Node removed = sentinel.prev;
if(removed == sentinel) {
throw new IllegalArgumentException("不能删除哨兵节点,非法!");
}
Node last = removed.prev;
Node next = sentinel;
last.next = next;
next.prev = last;
}
/**
* 根据索引删除指定元素
*
* @param value 待删除索引
*/
public void removeByValue(int value) {
Node remove = findByValue(value);
if(remove != null) {
Node last = remove.prev;
Node next = remove.next;
last.next = next;
next.prev = last;
}
}
public Node findByValue(int value) {
/* //方法一
for(Node p = sentinel.next; p != sentinel; p = p.next) {
if(p.value == value) {
return p;
}
}*/
//方法二
Node p = sentinel.next;
while(p != sentinel) {
if(p.value == value) {
return p;
}
p = p.next;
}
return null;
}
public Node findByIndex(int index) {
/* //方法一
int i=0;
for(Node p = sentinel.next; p != sentinel; p = p.next,i++) {
if(p.value == value) {
return p;
}
}*/
//方法二
int tIndex=index -1;
if(tIndex<-1){
throw new IllegalArgumentException(String.format("index [%d] 不合法%n", index));
}
Node p = sentinel.next;
int i = 0;
while(p != sentinel) {
if(i == tIndex) {
return p;
}
p = p.next;
i++;
}
return null;
}
/**
* 根据索引删除指定元素
*
* @param index 待删除索引
*/
public void remove(int index) {
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
Node p = sentinel.next;
@Override
public boolean hasNext() {
return p != sentinel;
}
@Override
public Integer next() {
int v = p.value;
p = p.next;
return v;
}
};
}
}