双向链表
节点类:
public class DLinkNode {
public int id;
public String name;
public DLinkNode next;
public DLinkNode prev;
public DLinkNode(int id, String name){
this.id = id;
this.name = name;
}
public void display(){
System.out.println("id-->" + id + ", name-->" + name);
}
}
主类:
public class DLinkList {
private DLinkNode first;
private DLinkNode last;
public boolean isEmpty(){
if(null == first)
return true;
return false;
}
public void insertFirst(int id, String name){
DLinkNode dLinkNode = new DLinkNode(id, name);
if(isEmpty()){
last = dLinkNode;
}else{
first.prev = dLinkNode;
}
dLinkNode.next = first;
first = dLinkNode;
}
public void insertLast(int id, String name){
DLinkNode dLinkNode = new DLinkNode(id, name);
if(isEmpty()){
first = dLinkNode;
}else{
last.next = dLinkNode;
dLinkNode.prev = last;
}
last = dLinkNode;
}
public void delFirst(){
if(isEmpty())
return;
if(first == last){
first = null;
last = null;
}else{
first = first.next;
first.next.prev = null;
}
}
public void delLast(){
if(isEmpty())
return;
if(first == last){
first = null;
last = null;
}else{
last = last.prev;
last.next = null;
}
}
public boolean delete(int id){
if(isEmpty()){
System.out.println("DLinkNode is null!");
return false;
}
DLinkNode current = first;
while(null != current){
if(current.id == id){
if(first == last){
first = null;
last = null;
}
if(current == first){
first = first.next;
}else if(current == last){
last = current.prev;
current.prev.next = null;
}else{
current.prev.next = current.next;
current.next.prev = current.prev;
}
return true;
}
current = current.next;
}
return false;
}
public void display(){
DLinkNode current = first;
if(isEmpty()){
System.out.println("DLinkList is empty!!");
return;
}
if(first == last){
first.display();
return;
}
while(null != current){
current.display();
current = current.next;
}
}
public static void main(String[] args){
DLinkList dl = new DLinkList();
dl.insertFirst(1, "ZhangSan");
dl.insertLast(2, "LiSi");
dl.insertLast(3, "WangWu");
// dl.delete(2);
// dl.delFirst();
dl.delLast();
dl.display();
}
}