/**
* 双端链表的实现
*/
class LinkA {
public long dData;
public LinkA next;
public LinkA(long d) {
dData = d;
}
public String toString() {
return "[" + dData + "]";
}
public void displayLink() {
System.out.println(toString());
}
}
class FirstLastList {
private LinkA first;// 头部
private LinkA last;// 尾部
public FirstLastList() {
first = null;
last = null;
}
public boolean isEmpty() {
return first == null;
}
/**
* 在头部插入节点
*/
public void insertFirst(LinkA l) {
if (isEmpty())
last = l;
l.next = first;
first = l;
}
/**
* 在尾部插入节点
*
* @param l
*/
public void insertLast(LinkA l) {
if (isEmpty())
first = l;
else
last.next = l;
last = l;
}
/**
* 从头部删除一个节点
*
* @return
*/
public long deleteFirst() {
long temp = first.dData;
if (first.next == null)
last = null;
first = first.next;
return temp;
}
public String toString() {
if (isEmpty())
return "{}";
LinkA current = first;
StringBuilder sb = new StringBuilder();
sb.append("{");
while (current != null) {
sb.append(current.toString()).append(",");
if (current.next == null)
break;
else
current = current.next;
}
sb.deleteCharAt(sb.length() - 1);
sb.append("}");
return sb.toString();
}
public void displayList() {
System.out.println(toString());
}
}
public class FirstLastListDemo {
public static void main(String[] args) {
FirstLastList fll = new FirstLastList();
for (int i = 1; i < 10; i++) {
System.out.println("插入:"+i);
if (i % 2 == 0)//i为偶数调用insertFirst
fll.insertFirst(new LinkA(i));
else//i为基数调用insertLast
fll.insertLast(new LinkA(i));
fll.displayList();
}
System.out.println("插入完毕开始从头部删除");
while(!fll.isEmpty()){
fll.deleteFirst();
fll.displayList();
}
}
}