1.实现双端链表
public class DoublePointLink {
private Node head;
private Node tail;
private int size;
private class Node{
private Object data;
private Node next;
public Node(Object data) {
// TODO Auto-generated constructor stub
this.data = data;
}
}
public DoublePointLink() {
// TODO Auto-generated constructor stub
head = null;
tail = null;
size = 0;
}
public void addHead(Object obj) {
Node node = new Node(obj);
if(size==0) {
head = node;
tail = node;
}else {
node.next = head;
head = node;
}
size++;
}
public void addTail(Object obj) {
Node node = new Node(obj);
if(size==0) {
head = node;
tail = node;
}else {
tail.next = node;
tail = node;
}
size++;
}
public void removeHead() {
if(size==0) {
throw new ArrayIndexOutOfBoundsException();
}else if(head.next==null) {
tail = null;
head = null;
}else {
head = head.next;
}
size--;
}
public void removeTail() {
if(size==0) {
throw new ArrayIndexOutOfBoundsException();
}else if(head.next==null) {
tail = null;
head = null;
}else {
int tempSize = size;
Node current = head;
Node previous = head;
while(tempSize>1) {
previous = current;
current = current.next;
tempSize--;
}
tail = previous;
previous.next = null;
}
size--;
}
public boolean isEmpty() {
return (size==0);
}
public void display() {
if(size>0) {
if(size==1) {
System.out.println("["+head.data+"]");
}else {
int tempSize = size;
Node current = head;
if(tempSize==1) {
System.out.println("["+head.data+"]");
return;
}
while(tempSize>0) {
if(current==head) {
System.out.print("["+current.data+"->");
}else if(current==tail) {
System.out.print(current.data+"]");
}else {
System.out.print(current.data+"->");
}
current = current.next;
tempSize--;
}
System.out.println();
}
}else {
System.out.println("[]");
}
}
}
2.使用
public class DoublePointLinkTest {
public static void main(String[] args) {
DoublePointLink dlink = new DoublePointLink();
dlink.addHead("aaa");
dlink.display();
dlink.addHead("bbb");
dlink.display();
dlink.addTail("ccc");
dlink.addTail("ddd");
dlink.display();
dlink.removeHead();
dlink.display();
dlink.removeTail();
dlink.display();
}
}
文章评论