写的中间发现一个问题,我试了一下,final修饰的引用是指该引用只能指向一个对象不能更改指向其他对象,但是该引用调该对象的方法进行内部信息修改是OK的
package 链表.循环链表;
import java.util.NoSuchElementException;
/**
* @author 芜情
* 带头结点的单向循环链表
*/
public class CLinkedList{
private static class Node{
private int data;
private Node next;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
Node(){
}
Node(int e, Node next){
data = e;
this.next = next;
}
}
private Node head;
private int size;
public CLinkedList() {
head = new Node();
head.setNext(null);
size = 0;
}
public boolean isEmpty(){
return head.getNext() == null;
}
public void clear(){
head.setNext(null);
}
public int size(){
return size;
}
private boolean isValidIndex(int index) {
return index >= 0 && index < size;
}
private boolean isValidPosition(int position) {
return position >= 0 && position <= size;
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkIndex(int index) {
if (!isValidIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPosition(int position) {
if (!isValidPosition(position))
throw new IndexOutOfBoundsException(outOfBoundsMsg(position));
}
private Node node(int index){
Node currentNode = head;
int i = 0;
while(i <= index){
currentNode = currentNode.getNext();
++i;
}
return currentNode;
}
/**
* 增加节点
*/
public void add(int position, int e){
checkPosition(position);
if(position == 0){
addFirst(e);
}else{
final Node positionNode = node(position - 1);
final Node node = new Node(e, positionNode.getNext());
positionNode.setNext(node);
++size;
}
}
public void addFirst(int e){
final Node last = node(size - 1);
final Node node = new Node(e, head.getNext());
head.setNext(node);
last.setNext(node);
++size;
}
public void addLast(int e){
if(isEmpty()){
addFirst(e);
}else{
final Node first = head.getNext();
final Node last = node(size - 1);
final Node node = new Node(e, first);
last.setNext(node);
++size;
}
}
public void add(int e){
addLast(e);
}
/**
* 删除节点
*/
public int remove(int index){
checkIndex(index);
if(index == 0){
return remove();
}else{
final Node node = node(index);
final Node beforeNode = node(index - 1);
beforeNode.setNext(node.getNext());
--size;
return node.getData();
}
}
public int removeFirst(){
final Node first = head.getNext();
if(first == null){
throw new NoSuchElementException();
}
final Node last = node(size - 1);
head.setNext(first.getNext());
last.setNext(first.getNext());
--size;
return first.getData();
}
public int remove(){
return removeFirst();
}
public int removeLast(){
if(isEmpty()){
throw new NoSuchElementException();
}
return remove(size - 1);
}
}