Java与数据结构:双向链表,实现简单功能:在某个位置插入、在链表末尾插入、指定位置删除、指定元素删除、判断是否为空、获取某个位置元素、遍历链表并打印等。(T为泛型,双向链表在定义是需指定类型,如String)
实现:
class Node <T>{//创建结点类,包括前驱、后继和数据域
public Node<T> next;
public Node<T> prio;
public T data;
}
public class doublelinkedlist<T>{//双向链表,包括头指针,尾指针和元素个数
protected Node<T> head;
protected Node<T> rear;
int num;
public doublelinkedlist(){
head = new Node();
rear = new Node();
head.next = rear;
rear.prio = head;
rear.next = null;
}
public boolean ListInsert(int pos,T value) {
if(pos>num||pos<0){//判断传入位置是否正确
System.out.println("Wrong! Fail to insert!");
return false;
}
else {
Node tmp = head;
int flag = 0;
for(int i=0;i<pos;i++) {//找到pos的节点,在该位置之前插入节点
tmp = tmp.next;
}
Node s = new Node();
s.data = value;
s.prio = tmp.prio;
tmp.prio.next = s;
s.next = tmp;
tmp.prio = s;
num++;
return true;
}
}
public boolean ListInsert(T value) {
num++;
Node s = new Node();
s.data = value;
s.next = rear;
rear.prio.next = s;
s.prio = rear.prio;
rear.prio = s;
return true;
}
public boolean isEmpty() {
if(head.next==rear)
return true;
else {
return false;
}
}
public boolean Delete(int pos) {
if(pos>num||pos<0){
System.out.println("Wrong! Fail to insert!");
return false;
}
Node tmp = head;
for(int i=0;i<pos;i++) {//找到pos的节点,删除该节点
tmp = tmp.next;
}
Node s = new Node();
s = tmp;
tmp.prio.next = s.next;
tmp.next.prio = s.prio;
num--;
return true;
}
public boolean Delete(T value) {
if(head.next==rear){
System.out.println("Wrong! Fail to insert!");
return false;
}
Node tmp = head;
int flag = 0;
for(int i=0;i<num;i++) {//找到pos的节点,删除该节点
tmp = tmp.next;
if(tmp.data.equals(value)) {
flag = 1;
break;
}
}
if(flag==0) {
return false;
}
Node s = new Node();
s = tmp;
tmp.prio.next = s.next;
tmp.next.prio = s.prio;
num--;
return true;
}
public int size() {
return num;
}
public T getData(int pos) {//返回某个位置的值
Node tmp = head;
int flag = 0;
for(int i=0;i<pos;i++) {//找到pos的节点
tmp = tmp.next;
}
return (T) tmp.data;
}
public boolean traverse() {
if(num==0) {
System.out.println("The List is empty.");
}
else {
Node s = head;
while(s.next!=rear) {
System.out.print(s.next.data+" ");
s=s.next;
}
}
System.out.println("over");
return true;
}
public static void main(String[] args) {//测试
doublelinkedlist<String> dl1 = new doublelinkedlist<String>();
//末尾插入元素
dl1.ListInsert("a");
dl1.ListInsert("b");
dl1.ListInsert("c");
System.out.println("插入元素后链表大小:"+dl1.size());
System.out.print("链表元素:");dl1.traverse();
//指定位置插入元素
dl1.ListInsert(2, "z");
System.out.println("插入元素后列表大小:"+dl1.size());
System.out.print("链表元素:");dl1.traverse();
//删除指定位置的元素
dl1.Delete(2);
System.out.println("删除元素后列表大小:"+dl1.size());
System.out.print("链表元素:");dl1.traverse();
//删除指定元素
dl1.Delete("a");
System.out.println("删除元素后列表大小:"+dl1.size());
System.out.print("链表元素:");dl1.traverse();
System.out.print("第2个的元素的值:");System.out.println(dl1.getData(2));
System.out.println("判断链表是否为空:"+dl1.isEmpty());
}
}