java版資料結構與演算法—雙端連結串列
阿新 • • 發佈:2018-11-29
/**
* 雙端連結串列
*/
class MyLinkList {
public Link first;
public Link last;
public MyLinkList(){
first = null;
last = null;
}
//判空
public boolean isEmpty(){
return first == null;
}
//從頭插入
public void insertFirst(int dd){
Link link = new Link(dd);
if(isEmpty()) {
last = link;
}
link.next = first;
first = link;
}
//從尾部插入
public void insertLast(int dd){
Link link = new Link(dd);
if(isEmpty()){
first = link;
}else {
last.next = link;
}
last = link;
}
//從開始位置刪除
public int deleteFirst(){
int temp = first.dData;
if(first.next == null){
last = null;
}
first = first.next;
return temp;
}
//列印
public void displayList(){
System.out.println("List(first -> last):" );
Link current = first;
while (current != null){
current.displayLink();
current = current.next;
}
System.out.println();
}
public static void main(String[] args){
MyLinkList myLinkList = new MyLinkList();
myLinkList.insertFirst(22);
myLinkList.insertFirst(44);
myLinkList.insertFirst(66);
myLinkList.insertLast(11);
myLinkList.insertLast(33);
myLinkList.insertLast(55);
myLinkList.displayList();
myLinkList.deleteFirst();
myLinkList.deleteFirst();
myLinkList.displayList();
}
}
class Link{
public int dData; //資料
public Link next; //下一個節點的引用
public Link(int d){
dData = d;
}
public void displayLink(){
System.out.print(dData + " ");
}
}