双向链表的操作:
查找;
增加;
删除;
package MyJava2;
public class DuLinkedList {
private class Node{
String data;
Node prve;
Node next;
public Node(){}
public Node(String data,Node prve,Node next){
this.data=data;
this.prve=prve;
this.next=next;
}
}
private Node header;
private Node tail;
private int size;
public DuLinkedList(){//创建空链表
header=null;
tail=null;
}
public DuLinkedList(String data){//根据指定元素创建链表
header=new Node(data,null,null);
tail=header;
size++;
}
public int len(){
return size;
}
public String getData(int index){//根据索引获得元素
return getNodeByIndex(index).data;
}
private Node getNodeByIndex(int index) {//根据索引获得指定节点
if(index<0||index>size-1){
throw new IndexOutOfBoundsException("OutOfIndex");
}
if(index<=size/2){
Node current=header;
for(int i=0;i<size/2&¤t!=null;i++,current=current.next){
if(i==index){
return current;
}
}
}
else {
Node current=tail;
for(int i=size-1;i>size/2&¤t!=null;i--,current=current.next){
if(i==index){
return current;
}
}
}
return null;
}
public int locate(String data){//获得指定元素的位置
Node current=header;
for(int i=0;i<size&¤t!=null;i++,current=current.next){
if(data.equals(current.data)){
return i;
}
}return -1;
}
public void addAtTail(String data){//尾插
if(header==null){
header=new Node(data,null,null);
tail=header;
}else{
Node newNode=new Node(data,tail,null);
tail.next=newNode;
tail=newNode;
}size++;
}
public void addAtHeader(String data){//头插
header=new Node(data,null,header);
if(tail==null){//插入之前是空表
tail=header;
}
size++;
}
public void add(String data,int index){//插入指定索引的元素
if(index<0||index>size){
throw new IndexOutOfBoundsException("OutOfIndex");
}
if(header==null){
addAtTail(data);
}else {
if(index==0){
addAtHeader(data);
}else {
Node prve=getNodeByIndex(index-1);
Node next=prve.next;
Node newNode=new Node(data,prve,next);
prve.next=newNode;
next.prve=newNode;
size++;
}
}
}
public String delData(int index){//删除指定索引的元素
if(index<0||index>size){
throw new IndexOutOfBoundsException("OutOfIndex");
}
Node delNode=null;
if(index==0){
delNode=header;
header=header.next;
header.prve=null;
}else {
Node prve=getNodeByIndex(index-1);
delNode=prve.next;
prve.next=delNode.next;
if(delNode.next!=null){
delNode.next.prve=prve;
}
delNode.prve=null;
delNode.next=null;
}return delNode.data;
}
public String remove(){//删除最后的元素
return delData(size-1);
}
public boolean empty(){
return size==0;
}
public void clear(){
header=null;
tail=null;
size=0;
}
public String toString(){
StringBuffer sb=new StringBuffer();
Node current=header;
for(;current!=null;current=current.next){
sb.append(current.data.toString()+",");
}
return sb.toString();
}
public static void main(String[] args) {
DuLinkedList d=new DuLinkedList();
d.addAtHeader("B");
d.add("A",0);
d.addAtTail("C");
System.out.println(d.toString());
System.out.println(d.size);
System.out.println(d.getNodeByIndex(2).data);
d.delData(0);
System.out.println(d.toString());
System.out.println(d.empty());
}
}