主要注意结构体的创建和双链表添加删除操作中结构图应用的改变。具体改变细节请看代码注释,代码不当之处希望各位加以提点,谢谢
/**
*
* <p>
* 功能描述:循环双链表
* </p>
*
* @author 钟良健
* @company
* @version V1.0
*/
public class util<T> {
private Node<T> head;
private int size;
@SuppressWarnings("hiding")
public class Node<T> {
private Node<T> next;
private Node<T> privious;
private T value;
public Node(Node<T> privious, Node<T> next, T value) {
this.privious = privious;
this.next = next;
this.value = value;
}
}
public util() {
head = new Node<T>(null, null, null);
head.privious = head.next = head;
size = 0;
}
/**
*
* 方法描述: 1、首先判断指定位置的节点是链表的前半段还是后半段 2、若为前半段则通过头节点的顺序查找 3、若为后半段则通过头节点的逆向查找
* 注意:1、默认头节点位置为0 2、注意for循环大小
*
* @param index
* @return 指定位置的节点
* @author 钟良健
*/
public Node<T> getNodeByIndex(int index) {
if (index == 0) {
System.out.println(head);
return head;
}
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("超出查找范围");
}
Node<T> node = null;
if (index < size / 2) {
for (int i = 0; i < index; i++) {
node = head.next;
}
System.out.println(node);
return node;
}
for (int j = 0; j < size - index + 1; j++) {
node = head.privious;
}
System.out.println(node);
return node;
}
/**
*
* 方法描述: 插入节点到指定位置节点处 1、首先根据插入节点的位置查找出原本位置的节点
* 2、new出一个新节点,新节点的前驱节点为原本位置节点的前驱节点,新节点的后驱节点为原本位置节点
* 3、原本位置节点的前驱节点的后驱节点指向新节点,原本位置的节点的前驱节点为新节点
*
* @param index
* 指定位置
* @param t
* 节点值
* @author 钟良健
*/
public void insertNodeByIndex(int index, T t) {
Node<T> oldPositionNode = getNodeByIndex(index);
Node<T> newPositionNode = new Node<T>(oldPositionNode.privious,
oldPositionNode, t);
oldPositionNode.privious.next = newPositionNode;
oldPositionNode.privious = newPositionNode;
size++;
}
/**
*
* 方法描述:
*
* @param index
* @author 钟良健
*/
public void deleteNodeByIndex(int index) {
Node<T> deleteNode = getNodeByIndex(index);
deleteNode.privious.next = deleteNode.next;
deleteNode.next.privious = deleteNode.privious;
deleteNode = null;
size--;
}
public void displaylist() {
Node<T> node = head;
for (int i = 0; i < size; i++) {
node = node.next;
System.out.println(node.value);
}
}
public static void main(String[] args) {
util<String> list = new util<String>();
list.insertNodeByIndex(0, "1");
list.insertNodeByIndex(0, "2");
list.insertNodeByIndex(0, "3");
list.insertNodeByIndex(0, "4");
list.displaylist();
}
}